SoftJellyfish
SoftJellyfish

Reputation: 37

2 classes with the same name within namespaces

I have gone back to learning C++ doing some old university courses and I am now currently learning parametric polymorphism as well as creating my own namespaces. The exercise states that I have to make a namespace called "Federation" which has a class called "Ship" that takes values and one default value that never changes. inside the federation namespace there is also a "Starfleet" namespace in which we also have a "Ship" class, the only difference is that the default value stated before can be specified by the user.

Here is the code:

Federation.hpp

#include <iostream>
#include <string>
#include <cstring>

namespace Federation
{
  namespace Starfleet 
  {
    class Ship
    {
    public:
      Ship(int length, int width, std::string name, short maxWarp);
      ~Ship();
    private:
      int _length;
      int _width;
      std::string _name;
      short _maxWarp;
    };
  };
  class Ship
  {
  public:
    Ship(int length, int width, std::string name);
    ~Ship();
  private:
    int _length;
    int _width;
    std::string _name;
  }
};

Federation.cpp

#include "Federation.hpp"
using namespac std;

Federation::Starfleet::Ship::Ship(int length, int width, string name, short maxWarp): _length(length), _width(width), _name(name), _maxWarp(maxWarp)
{
  cout << "Starfleet Ship Created." << endl;
}

Federation::Starfleet::Ship::~Ship()
{

}

Federation::Ship::Ship(int length, int width, string name, int speed = 1): _length(length), _width(width), _name(name)
{
  cout << "Regular Ship Created"
}

Federation::Ship::~Ship()
{

}

main.cpp

#include "Federation.hpp"

int main(int ac, char **av)
{
  Federation::Starfleet::Ship mainShip(10, 10, "Starfleet Ship", 20);
  Federation::Ship smallShip(5, 5, "Small Ship");
}

When compiling I get this Error: "prototye for Federation::Ship::Ship(int, int, std::__cxx11::string, int) does not match any class in Federation::Ship"

I am totally lost as to what this means, when I look at my functions on my hpp file all of them seem to be correct, so I don't really understand what exactly I'm doing wrong in this case.

Upvotes: 1

Views: 122

Answers (1)

This has nothing to do with namespaces. You declare the c'tor with a certain prototype in the header:

Ship(int length, int width, std::string name);

And then randomly add a parameter with a default argument in the implementation file:

Federation::Ship::Ship(int length, int width, string name, int speed = 1)

Argument types are a part of any function or constructor's signature. So you have a declaration and definition mismatch. Declare the extra parameter in the header (along with the default argument).

Ship(int length, int width, string name, int speed = 1);
// and
Federation::Ship::Ship(int length, int width, string name, int speed)

Upvotes: 4

Related Questions