Home > Net >  How to seperate definition and implementation of a derived class constructor?
How to seperate definition and implementation of a derived class constructor?

Time:12-07

I would like to learn how to define a derived class constructor in one file so that I could implement it in another file.

public:
Derived(std::string name) : Base(name);
~Derived();

Destructor works as expected, however with constructor I either add {} at the end (instead of a semicolon) and then get redefinition of 'Derived' error or I get asked to add {} instead of a semicolon. What is a way to separate definition and implementation in this case?

CodePudding user response:

Base.h

#include <string>

class Base
{
protected:
    std::string name;
    ...
public:
    Base(std::string name);
    virtual ~Derived();
    ...
};

Base.cpp

#include "Base.h"

Base::Base(std::string name)
    : name(name)
{
    ...
}

Base::~Base()
{
    ...
}

Derived.h

#include "Base.h"

class Derived : public Base {
    ...
public:
    Derived(std::string name);
    ~Derived();
    ...
};

Derived.cpp

#include "Derived.h"

Derived::Derived(std::string name)
    : Base(name)
{
    ...
}

Derived::~Derived()
{
    ...
}

CodePudding user response:

You do it the same way as for any other member function of the class. For example,

base.h

#pragma once 

#include <string>

class Base 
{
    std::string name;
    public:
        Base() = default;
        Base(std::string pname);//declaration
        //other members
};

base.cpp

#include "base.h"
#include <iostream>
//definition
Base::Base(std::string pname): name(pname)
{
    std::cout<<"Base constructor ran"<<std::endl;
    
}

derived.h

#pragma once
#include "base.h"
class Derived : public Base
{
  public: 
    Derived(std::string pname);//declaration
};

derived.cpp

#include "derived.h"
#include <iostream>
//definition
Derived::Derived(std::string pname): Base(pname)
{
    std::cout<<"Derived constructor ran"<<std::endl;
}

main.cpp


#include <iostream>
#include "derived.h"
#include "base.h"

int main()
{
    
    Derived d("anoop");
    return 0;
}

CodePudding user response:

You can separate declaration and definition like so:

class Derived : public Base {
public:
   Derived(std::string name); // declaration
   // ... other members here
};

Then, elsewhere:

// definition
Derived::Derived(std::string name) : Base(name) {
  // ...
}
  • Related