Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining constructor for struct declared inside a class in C++

Tags:

c++

How can I declare constructor for a struct? My struct is declared in the private part of a class and I want to declare my constructor for it.

Below is my code

class Datastructure {

private:

        struct Ship
        {
            std::string s_class;
            std::string name;
            unsigned int length;

        } minShip, maxShip; 

        std::vector<Ship> shipVector;
public:

    Datastructure();
    ~Datastructure();
};

This my header file; how can I declare constructor for my struct Ship and where do I have to implement that constructor in .h file or in cpp file?

like image 482
Abdul Samad Avatar asked Jun 07 '26 22:06

Abdul Samad


2 Answers

Constructor declared in header file

struct Ship
{
    Ship();
    std::string s_class;
    std::string name;
    unsigned int length;

    } minShip, maxShip; 

and implemented in code:

DataStructure::Ship::Ship()
{
  // build the ship here
}

or more likely:

DataStructure::Ship::Ship(const string& shipClass, const string& name, 
                          const unsigned int len) :
s_class(shipClass), name(_name), length(len)
{
}

with this in the header:

    struct Ship
    {
private:
        Ship();
public:
        Ship(const string& shipClass, const string& name, unsigned len);
        std::string s_class;
        std::string name;
        unsigned int length;

        } minShip, maxShip; 
like image 67
Steve Townsend Avatar answered Jun 10 '26 11:06

Steve Townsend


You declare it the same way you declare any other constrctor

class Datastructure {
private:
  struct Ship
  {
    std::string s_class;
    std::string name;
    unsigned int length;

    Ship(); // <- here it is

  } minShip, maxShip; 

  std::vector<Ship> shipVector;
public:
  Datastructure();
  ~Datastructure();
};

And you define it the same way you define any other constructor. If it is inline, you define it in the header file. If it is not inline, you define it in implementation file

Datastructure::Ship::Ship()
{
  // whatever
}
like image 37
AnT Avatar answered Jun 10 '26 12:06

AnT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!