Inherited member function accessing data members - c++

Consider the sample code below:
#include <iostream>
using namespace std;
class A
{
private:
static int a;
int b;
protected:
public:
A() : b(0) {}
void modify()
{
a++;
b++;
}
void display()
{
cout << a <<"\n";
cout << b <<"\n";
}
};
int A::a=0;
class B : public A {
private:
int b;
public:
B(): b(5)
{
}
};
int main()
{
A ob1;
B ob2;
ob1.display();
ob2.display();
return 0;
}
In the code above, the class A has a private data member band class B also has a private data member b. The function display() is used to display the data members.
When i invoke display() using ob1.display(), display() accesses the private data member b of class A. I understand that. But when i invoke display using ob2.display, which b does display() access? Is it the b of class A or b of class B? Kindly explain the why it accesses class A's b or class B's b

It will access A::b. The display method implementation in class A has no clue about the existence of B::b at all, let alone using it. For all intents and purposes, B::b is separate from A::b. Only in the scope of B itself, the name conflict makes b refer to B::b, hiding A::b. Member variables cannot be virtual.

ob2.display() will access the derived class member.
The member function call is always evaluated on this, this->display() the this in case points to object of your Base class and hence any reference to b inside the display() function is evaluated as this->b which is b of the Base class.
This is because display() of the Base class has no knowledge of whether any other class derives from it. Base class is always independent of the Derived class. To solve a problem the uual pattern followed is to provide a display() method in the Derived class which then in turn calls the dsiplay() method of the Base class.
void B::display()
{
//cout << a <<"\n";
cout << b <<"\n";
A::display();
}

It is class A. A::display() cannot access B private members.

Related

How to call class A's method 1 which invokes class B's method 2 in C++?

I have a base class A and hope to create a class B with very similar functionality. I want class B to have a function to call class A's func1(), but when calling it, the func2() is replaced/over-rided by class B's func2(). My goal is to avoid repeated code and not modify class A. The inheritance implementation below does not work. Should I use inheritance here? How can I achieve my goal?
#include <iostream>
using namespace std;
class A {
public:
void func1() {
func2();
cout << "class A fun1" << endl;
}
private:
void func2() {
cout << "class A fun2" << endl;
}
};
class B : A{
public:
void func3() {
func1();
cout << "class B fun3" << endl;
}
private:
void func2() {
cout << "class B fun2" << endl;
}
};
int main() {
B b;
b.func3();
return 0;
}
The current output is:
class A fun2
class A fun1
class B fun3
But what I want is:
class B fun2
class A fun1
class B fun3
You should use virtual function for that. When a function is declared as virtual, the compiler only uses the implementation of the virtual function that is present in the derived class.
The function in the base class cannot be used directly from the base class. As in, if you create an object for the class A, you won’t be able to call func2() if it’s declared as virtual.
Note: You'll be able to call the virtual function from the derived class even though the virtual function definition is not present in the derived class (because it'll anyways be inherited and you'll be calling the inherited copy of the virtual function).
Hope it helps. Happy coding! :)

cpp inheritance some misconception

here i have some code
class A{
private:
int a;
public:
void abc()
{ cout << a << endl; }
};
class B : public A
{ };
main() {
B obj;
obj.abc(); // it works but why? obj.abc is printing a which should not inherit to class B because it is private.
ok so derived class inherited a public function abc() from the base class and that function is trying to output a member variable a that is not a part of derived class because it is private in base class? So how does it do that. this code prints a... but how?
a is private to class A, but since function abc is defined in class A, abc can make use of a.
B can make use of abc because abc is public and B derives from A (publicly).
a would not be available to functions defined in B.

Confusion with virtual keyword in C++

I was studying on effects of virtual keyword in C++ and I came up with this code.
#include<iostream>
using namespace std;
class A {
public:
virtual void show(){
cout << "A \n";
}
};
class B : public A {
public:
void show(){
cout << "B \n";
}
};
class C : public B {
public:
void show(){
cout << "C \n";
}
};
int main(){
A *ab = new B;
A *ac = new C;
B *bc = new C;
ab->show();
ac->show();
bc->show();
}
The expected output is:
B
C
B
Since show function in B is non-virtual. But the outcome when you compile this is:
B
C
C
It behaves as if show function in B is virtual. Why is this the case? Does B class gets overridden here? How come I point to the A class if I'm pointing a C class to the B class?
According to the C++ 2017 Standard (10.1.2 Function specifiers)
2 The virtual specifier shall be used only in the initial declaration
of a non-static class member function; see 13.3.
And (13.3 Virtual functions)
2 If a virtual member function vf is declared in a class Base and in
a class Derived, derived directly or indirectly from Base, a member
function vf with the same name, parameter-type-list (11.3.5),
cv-qualification, and ref-qualifier (or absence of same) as Base::vf
is declared, then Derived::vf is also virtual (whether or not it is so
declared) and it overrides111 Base::vf. For convenience we say that
any virtual function overrides itself. A virtual member function C::vf
of a class object S is a final overrider unless the most derived class
(4.5) of which S is a base class subobject (if any) declares or
inherits another member function that overrides vf. In a derived
class, if a virtual member function of a base class subobject has more
than one final overrider the program is ill-formed.
Thus the function show in the class B is a virtual function because it has the same signature as the function declared in the class A.
Consider a more interesting example when in the class B there is added the qualifier const to the member function show.
#include<iostream>
using namespace std;
class A {
public:
virtual void show(){
cout << "A \n";
}
};
class B : public A {
public:
void show() const{
cout << "B \n";
}
};
class C : public B {
public:
void show() {
cout << "C \n";
}
};
int main(){
A *ab = new B;
A *ac = new C;
B *bc = new C;
ab->show();
ac->show();
bc->show();
}
In this case the output will look like
A
C
B
In this expression statement
ab->show();
there is called the virtual function show declared in the class A.
In this statement
ac->show();
there is called the same virtual function that is overridden in the class C. The compier uses the virtual function declaration in the class A because the static type of the pointer ac is A *.
In this statement
bc->show();
there is called non-virtual member function show with the qualifier const because the static type of the pointer bc is B * and the compiler finds the function in the class B that hides the virtual function declared in the class A..
For the original program you could use the specifier override to make the class definitions more clear. For example
#include<iostream>
using namespace std;
class A {
public:
virtual void show(){
cout << "A \n";
}
};
class B : public A {
public:
void show() override{
cout << "B \n";
}
};
class C : public B {
public:
void show() override{
cout << "C \n";
}
};
int main(){
A *ab = new B;
A *ac = new C;
B *bc = new C;
ab->show();
ac->show();
bc->show();
}
You don't need to specify a function as virtual in derived class, if specified in the base class.
The behaviour is the correct one. Since the show function is virtual, the version invoked will be the one attached to the instance you're calling it on, rather than the one described by the type of that instance (which can be a base of that instance's real type).

Simple Inheritance in C++

In the given program Class B has inherited Class A and in main() object of class B is created and getdata() function is invoked, why does class B's getdata() is called??
class A {public: void getdata() { cout<<"Class A"; } };
class B: public A { public: void getdata() { cout<<"Class B"; } };
void main() { B b1; b1.getdata(); }
why does class B's getdata() is called??
Because b1 is an object of type B.
Non-virtual member functions are resolved according to the static type of the variable that invokes them.
In the case you gave, the variable that invokes getdata() is b1, which is of type B. Therefore, B::getdata() is invoked.
In the link you provided, http://www.tutorialspoint.com/cplusplus/cpp_polymorphism.htm , area is invoked through a pointer of type Shape*, therefore, Shape::area() is invoked.
Consider also this program: http://ideone.com/KVjN3
#include <iostream>
class A {public: void getdata() { std::cout<<"Class A\n"; } };
class B: public A { public: void getdata() { std::cout<<"Class B\n"; } };
int main() { B b1; b1.getdata(); A* pa = &b1; pa->getdata(); }
output:
Class B
Class A
It is very similar to your program. The first invocation of getdata() is through a B, therefore B::getdata() is invoked. The second is through an A*, therefore A::getdata() is invoked.
All of this changes, however, if you supply the virtual keyword.
Because b1 is declared statically as a variable of type B.
Note that in this situation the fact that getdata() is not virtual is not relevant because of the reason written here above.
C++ objects aren't polymorphic by nature (as opposed to Java).
You have to declare the functions with the "virtual" key in order to achieve polymorphism

Accessing overridden base class member from derived class object

I have two classes:
class A
{
public:
int i;
};
class B : public A
{
public:
int i;
};
Suppose that I created an object for class B
B b;
Is it possible to access A::i using b?
Is it possible to access A::i using b?
Yes!
How about b.A::i? ;)
Yes:
int main()
{
B b;
b.i = 3;
b.A::i = 5;
A *pA = &b;
B *pB = &b;
std::cout << pA->i << std::endl;
std::cout << pB->i << std::endl;
}
Yes you can. To find out read this
An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method.
From within the derived class that has an override method, you still can access the overridden base method that has the same name by using the base keyword. For example, if you have a virtual method MyMethod(), and an override method on a derived class, you can access the virtual method from the derived class by using the call:
base.MyMethod()
Two ways:
struct A{
A():i(1){}
int i;
};
struct B : A{
B():i(0), A(){}
int i;
};
int main(){
B b;
cout << b.A::i;
cout << (static_cast<A&>(b)).i;
}
It is possible, as others replied.
But in the example you posted, the base and derived members are the same, the data type was not overriden.
This would be relevant in the case of derived classes that define a new data type for the base members as shown in this post: C++ Inheritance. Changing Object data Types