same data members in both base and derived class
The width
and height
data members in B
hide (or shadow) those in A
.
They serve no useful purpose in this case and should be removed
If you want to access the hidden (or shadowed) data members, you can use scope resolution:
int area()
{
return (A::width * A::height);
}
Related videos on Youtube
nagaradderKantesh
Updated on September 16, 2022Comments
-
nagaradderKantesh over 1 year
I am new to C++ programming, i am reading inheritance concept, i have a doubt about inheritance concept which is: what will happen if the base and derived class have same data members. And also please go through my code as below:
#include "stdafx.h" #include <iostream> using namespace std; class ClassA { protected : int width, height; public : void set_values(int x, int y) { width = x; height = y; } }; class ClassB : public ClassA { int width, height; public : int area() { return (width * height); } }; int main() { ClassB Obj; Obj.set_values(10, 20); cout << Obj.area() << endl; return 0; }
In the above i am declaring data members with the same name as Base class data members, and i called the
set_values()
function with the derived Class Object to initialize the data memberswidth
andheight
.When i call the
area()
function, why did it return some garbage value instead of returning the proper value. And it is happening only when i declare data members with same name as base class data members in derived class. If i remove the data members declared in derived class it is working fine. So what is the problem with declaration in derived class? please help me. -
nagaradderKantesh about 11 yearsokay fine.. but derived class inheriting the set_values() function na then why it is not initializing the data members declared in the derived class.
-
Aesthete about 11 yearsBecause the base class doesn't know about the members of the derived class. Try removing
width
andheight
fromClassA
and see what happens. -
nagaradderKantesh about 11 yearsokay..if i removed that it will work fine. let us assume there are no data member declarations in derived class, and when i call set_values() function it initialize the base class's width and height members and same will be reflected in area() function but if declare the data members in derived why set_values() function not initializing the derived class data members even though it is inherited by derived class .
-
johnsyweb about 11 yearsBecause the base class doesn't know about the members of the derived class, as @Aesthete said. The derived class has public access to the members of its base class(es) but not the other way around. This is how inheritance works.
-
Zebrafish over 7 yearsIs this because the members are bound at compile time? If the function was virtual I think it would act on the derived class's members.