Reputation: 2605
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
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
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:
mBase
protectedUpvotes: 1
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