waas1919
waas1919

Reputation: 2605

C++ How to create base class which creates derived class object, and access private members of base class?

Is there any way I can have a derived class that access the private members of the base class, and at the same time be able to create a derived object on a base class method inside the base class?

Something like this:

class Derived;

class Base
{
public:
    void func()
    {
        // I want to create the derived obj here
        Derived derived;
        derived.func();
    }
public:
    int mBase = 5;
};

class Derived : public Base
{
public:
    void func()
    {
        // I need to have access to the private members of Base inside this method
        mBase = 6; 
    }
};

The error is the following:

Error: derived uses undefined class Derived.

How can I do something like this?

Thank you

Upvotes: 0

Views: 7947

Answers (3)

Useless
Useless

Reputation: 67743

a derived class that access the private members of the base class

Usually just by writing protected instead of private. Is there some reason you can't do that?

Error: derived uses undefined class Derived.

Just declare func in the base class definition, and only define it after the derived class has been defined:

class Base {
public:
    void func();
protected:
    int mBase = 5;
};

class Derived : public Base {
public:
    void func() {
        mBase = 6; 
    }
};

void Base::func() {
    Derived derived;
    derived.func();
}

Upvotes: 3

O'Neil
O'Neil

Reputation: 3849

You should read about polymorphism. What you probably want is make func() virtual:

class Base
{
public:
    virtual void func() { /* Base behavior */ } // or pure = 0
    virtual ~Base() = default; // don't forget!
public:
    int mBase = 5;
};

class Derived : public Base
{
public:
    void func() override
    {
        // Derived behavior
    }
};

About accessing Base::mBase, you have two options:

  • make mBase protected
  • add a protected setter that you use in Derived to modify it.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409196

To be able to use the Derived class and call member function in it (which includes the constructor and destructor) the full definition needs to be available. In this case it isn't in the Base::func function.

The solution is simple: Don't define func inline, just declare it and then implement (define) it after the Derived class have been defined.

Upvotes: 5

Related Questions