Search code examples
c++derived-class

C++ How to make derived class to take base class parameters automatically


When I change a value in base class and then, later on, create an object of the child class, child class created with an empty parameter instead of the changed value. Is there a way to object of derived class with the parameters of the base class?

Example:

Base.h

class Base
{

class Child;

public:
    int number = 0;
    Child *chilObject;

    void Setup()
    {
         number = 5;
         childObject = new Child;
    }
};

Child.h

class Child :
    public Base
    {

    };

main

int main()
{
    Base base;   
    base.Setup();

    cout << base.number << " : " << base->chilObject.number << endl;
    cout <<  << endl;        
}

Output: 5 : 0

I am simply asking if there is a way to make the derived class object to take Base class variables automatically.


Solution

  • Here is how it is typically done in C++:

    #include <iostream>
    
    class Base
    {
    
    public:
    
        int number = 0;
    
        virtual ~Base() = default;
    
        void Setup()
        {
            number = 5;
        }
    };
    
    class Child : public Base
    {
        // number exists here because of inheritance.
    };
    
    int main()
    {
        // Child object seen as Base object:
        Base* base = new Child;
        base->Setup();
    
        // Child object seen as Child object:
        Child* child = static_cast< Child* >( base );
    
        // Both share the same 'number' variable, so:
    
        std::cout << base->number << " : " << child->number << std::endl;
        std::cout << std::endl;
    
        // Free memory taken by 'new'.
        delete base;
    
        return 0;
    }
    

    yields:

    5 : 5
    

    In real code, you would probably make Setup virtual and not cast though.