it could be not good question and i know i need more time to learn about it
but i'm really wondering how to make it work
here is my code
#include <bits/stdc .h>
using namespace std;
class Parent{
protected:
int value;
int size;
public:
Parent();
Parent(const Parent &p);
};
Parent::Parent()
{
this->value = 0;
this->size = 0;
}
Parent::Parent(const Parent &p)
{
this->value = p.value;
this->size = p.size;
}
class Child:public Parent{
public:
Child();
Child(const Parent& p);
};
Child::Child()
{
this->value = 0;
this->size = 0;
}
Child::Child(const Parent& p)
{
this->value = ??
this->size = ??
}
as i want to use parent class as a parameter in an inherited child class,
the problem is i can't use p.size or p.value in child class.
is there any way to solve this problem?
thank u for read this.
CodePudding user response:
When you implement a class, you also have to use its constructors in each of your derived class constructors.
In your case: Child::Child(const Parent& p) : Parent(p) {}
CodePudding user response:
This Child(const Parent& p);
is not a proper copy constructor. A copy constructor for a class T
takes a &T
(possibly with CV-qualifier) as argument. In this case it should be Child(const Child& p);
.
Furthermore, if we look at https://en.cppreference.com/w/cpp/language/access, then we can see that:
A protected member of a class is only accessible
- to the members and friends of that class;
- to the members and friends (until C 17) of any derived class of that class, but only when the class of the object through which the protected member is accessed is that derived class or a derived class of that derived class
So a function in Child
that takes a Child
as argument has access to that other Child
s protected members, but a function that takes a Parent
does not have access to that Parent
s protected members.
For example, if you have a Button
and TextBox
that both inherit from UIWidget
, then the Button
can access UIWidget
protected members in other Button
s, but not in TextBox
es.
Edit:
If you really want to have a constructor that takes a Parent
as argument, then you can do as Roy Avidan suggests in his answer, and do this:
Child::Child(const Parent& p)
: Parent(p) // <- Call the Parent copy constructor
{
// No access to protected members of p here!
}
This works because it calls the copy constructor of Parent
with a Parent
argument, which means that any access to the protected members of Parent
happens in Parent
. Note that any access to a protected member of p
in the body is an access violation of p
.