Simple Inheritance in C++ - 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

Related

Base class method alias

Let's consider the following code:
#include <iostream>
class Base
{
public:
void foo() //Here we have some method called foo.
{
std::cout << "Base::foo()\n";
}
};
class Derived : public Base
{
public:
void foo() //Here we override the Base::foo() with Derived::foo()
{
std::cout << "Derived::foo()\n";
}
};
int main()
{
Base *base1 = new Base;
Derived *der1 = new Derived;
base1->foo(); //Prints "Base::foo()"
der1->foo(); //Prints "Derived::foo()"
}
If I have the above stated classes, I can call the foo method from any of Base or Derived classes instances, depending on what ::foo() I need. But there is some kind of problem: what if I need the Derived class instance, but I do need to call the Base::foo() method from this instance?
The solve of this problem may be next:
I paste the next method to the class Derived
public:
void fooBase()
{
Base::foo();
}
and call Derived::fooBase() when I need Base::foo() method from Derived class instance.
The question is can I do this using using directive with something like this:
using Base::foo=fooBase; //I know this would not compile.
?
der1->Base::foo(); //Prints "Base::foo()"
You can call base class method using scope resolution to specify the function version and resolve the ambiguity which is useful when you don't want to use the default resolution.
Similar (Not exactly same case) example is mentioned # cppreference
struct B { virtual void foo(); };
struct D : B { void foo() override; };
int main()
{
D x;
B& b = x;
b.foo(); // calls D::foo (virtual dispatch)
b.B::foo(); // calls B::foo (static dispatch)
}

How to call virtual function for all created objects which are inherited from the one? C++

For example, I have three classes: A, B::A and C::A, only B and C have virtual method print(), like that:
#include <iostream>
using namespace std;
class A {
public:
virtual void print() {
return;
//do nothing
}
static void Func() {
//how to call all virtual functions print() for one class A?
print(); //doesn't work
}
};
class B : public A {
public:
virtual void print() {
cout << "B" << endl;
}
};
class C : public A {
public:
virtual void print() {
cout << "C" << endl;
}
};
int main() {
B b1;
B b2
C c;
A::Func();
return 0;
}
I wan't use print() for all inherited objects (b1, b2, c) by using just class A. How can I do it?
Declare a static class member of A that's a container of pointers to all instances of A or its subclasses. A std::list will be an excellent choice:
class A {
static std::list<A *> all_instances;
public:
// ...
};
In A's constructor, add its this to the list, saving the new list entry's iterator. In A's destructor, remove its list entry from the list.
So now you will have a private container that enumerates all instances of A, or any of its subclasses.
Writing a static class method that invokes each one's print() method becomes trivial, at this point.
Of course, a little bit of additional work is necessary to implement thread safety, if it's an issue here.
Writing the code for A's constructor or destructor will be your homework assignment.

C++ inheritence calling base class member function using derived class

May be my question is wrong. I am new to C++.
Is there any way call a base class member function using derived class object if that function is being overridden in derived class?
For example:
class A {
public:
void add() { cout<<"A"; }
};
class B: public A {
public:
void add() { cout<<"B"; }
};
int main() {
B bObj;
bObj.add(); // calls member function of class B
return 0;
}
First of all, you aren't really overriding the add function, merely hiding the name, since A::add is not declared virtual.
To call A::add, just be explicit about it:
bObj.A::add();
Typically, B::add() exists for a reason and you probably shouldn't be calling A::add() on a B. Which isn't to say you can't - you just have to turn it into an A first:
B bObj;
static_cast<A&>(b).add(); // calls A::add()
Or explicitly specify that it's A::add():
bObj.A::add();
From within B, you have to qualify the call:
class B: public A {
public:
void add() { cout<<"B"; }
void test() {
add(); // calls B::add
A::add(); // calls A::add
}
};

Private function member called outside of class

In the example below, why is B::f() called even though it is private?
I know this fact that :
Access is checked at the call point using the type of the expression used to denote the object for which the member function is called.
#include <iostream>
class A {
public:
virtual void f() { std::cout << "virtual_function"; }
};
class B : public A {
private:
void f() { std::cout << "private_function"; }
};
void C(A &g) { g.f(); }
int main() {
B b;
C(b);
}
Because the standard says so:
[C++11: 11.5/1]: The access rules (Clause 11) for a virtual function are determined by its declaration and are not affected by the rules for a function that later overrides it. [ Example:
class B {
public:
virtual int f();
};
class D : public B {
private:
int f();
};
void f() {
D d;
B* pb = &d;
D* pd = &d;
pb->f(); // OK: B::f() is public,
// D::f() is invoked
pd->f(); // error: D::f() is private
}
—end example ]
The example is the same as yours, lol.
private functions can override public virtual functions from a base class. Accessability is, in a fact, completely ignored when determining whether a function overrides another, so even in
// Redundant private for clarity:
class A { private: virtual void foo(); };
class B : A { public: void foo(); };
B::foo overrides A::foo.
During compile time C++ compiler verifies accessibility of functions and methods based on their type. In function C variable g is of type A (checked during compilation of the code), in which method f is declared as public.
Take a look at this link

Inherited member function accessing data members

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.