Reputation: 13
I'm new to C++ and programming, so bear with me: I'm trying to store a string in my parent class for later use in a child class. But when I try to use my string in my child class, it doesn't output anything.
class parent
{
protected:
std::string str;
public:
void input()
{
std::cin >> str;
}
};
class child : parent
{
public:
void output()
{
std::cout << str << std::endl;
}
};
int main()
{
parent parent;
child child;
parent.input();
child.output();
return 0;
}
This also happens if I try to use an integer from my parent class. But for some reason, the code works, if I define my string or integer in the child class.
class child : parent
{
public:
void output()
{
std::cin >> str >> std::endl;
std::cout << str << std::endl;
}
};
Thank you for your time reading my amateur question!
Upvotes: 0
Views: 205
Reputation: 117298
First a note on inheritance. This
class child : parent
will use the default, private
inheritance. It's the same as writing
class child : private parent
and it means that the parents public
and protected
members will be private
in the child, hence the input()
method will be unavailable from outside the child. The code should therefor not compile, if you later try to call the input()
method on a child instance (i.e. from the outside). When starting with C++ you almost always want to make the inheritance public. So change it to:
class child : public parent
or
struct child : /* public */ parent // struct has 'public' inheritance by default
You later create one parent
and one child
instance. I renamed the instances p
and c
for clarity. You should generally avoid using the same name for instances as for classes.
parent p;
child c;
p.input();
c.output();
p
now contains (is composed of) one std::string
instance named str
. c
also has one std::string
instance named str
, but they are different instances/objects (unless you make them static
, but for now, don't). Each instance carries its own data. Even two instances of the same class do, so this would not repeat anything back either:
child c1, c2;
c1.input();
c2.output();
However, this will work, since the same instance is used for both input and output:
child c;
c.input();
c.output();
Upvotes: 1
Reputation: 385144
You have two individual class instances, not one. A parent
, and a child
(which inherits from parent
). The two instances are unrelated and unconnected; modifying one does not influence the other, despite the inheritance heirarchy that's in place.
I think you meant this:
int main()
{
child obj;
obj.input();
obj.output();
}
Now, though input()
comes from the inherited parent
part of the object, you're calling both functions on the same object with the same, shared state, and ought to see the expected result accordingly.
Upvotes: 3