I am trying to get through the concept of Inheritance (testing in C++). Here a quote from: http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)
“In object-oriented programming (OOP), inheritance is a way to reuse code of existing objects, or to establish a subtype from an existing object, or both, depending upon programming language support”
Then I tested this code:
class Person
{
public:
int ii;
Person():ii(0){}
};
class Student : public Person
{
};
class Student1 : public Person
{
};
Then,
Person p;
Student s;
Student1 s1;
s.ii = 222;
p.ii = 333;
cout << s.ii << endl; // prints 222
cout << s1.ii << endl; // prints 0
cout << p.ii << endl; // prints 333
As shown in the results, each of the sub class has its own version of ii variable and each one the get the copy value from the base class. Therefore, when we changed one, it doesn’t affect the others.
That’s not what I got in mind at first place. I thought that when inheriting from a base class, all sub classes will inherit the same instance of attributes. Each sub class does not need to keep its own versions. And that can take the advantages of re-use and space saving.
Am I misunderstanding something? And if I am correct, is it true for other OOP languages, too?
(I know I can use static variable to reach my thought, but that’s not what I am talking about)
You have three instances of the classes so they are independent. Meaning the subclasses don’t have to declare
ii. Think of the classes like templates (don’t confuse them with the language construct template though) and then you create instances of them.You wouldn’t want all Persons to always have the same field values would you?
Having said that, you might be looking for (probably not/hopefully not) static variables.
Look up instances and classes in object orientation.