Search code examples
c++oopinheritanceconstructorderived-class

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


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?


Solution

  • 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()
    {
        ...
    }