inheritance,class,c++

#include<iostream>
using namespace std;

class a
{

public:
void add()
{
cout<<"in A";
}
void fn()
{
add();
}
};
class b: public a
{
public:
void add()
{
cout<<"in b";
}

};
int main()
{
b d;
d.fn();
return 0;

}
// in this code why a::add() invoke but i think b::add() called because d is the type of class b
If you want to call the version of function a() depending on the dynamic type of the object you should make the function a virtual function.
1
2
3
4
5
6
7
8
9
10
11
12
class a
{
public:
	virtual void add()
	{
		cout<<"in A";
	}
	void fn()
	{
		add();
	}
};
Why would b::add invoked and not a::add?

Just for fun, add this in main():
1
2
d.a::add();
d.b::add();


Both a::add and b::add are exist at the same time in your class. And as class a does not know that anything is derived from it, all functions of class a uses class a functions only.
To achieve dynamic binding (selection of function depending on real variable type) make add virtual.
https://isocpp.org/wiki/faq/virtual-functions
http://www.learncpp.com/cpp-tutorial/122-virtual-functions/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>

class a
{
public:
    virtual void add()
    { std::cout << "in A"; }

    void fn()
    { add(); }
};

class b: public a
{
public:
    virtual void add() override
    { std::cout << "in b"; }
};

int main()
{
    b d;
    d.fn();
}

http://ideone.com/4Joobo
i know if i make a::add() virtual then b::add() invoke
but want to know here that why b::add() not invoke in this code?
Last edited on
because fn is told to call a::add and not b::add. Also it is not told to try to see overridden function in derived classes (what virtual do).

Remember: you might think that both a and b contains function with the same name, but thanks to name mangling those functions have completely different names.

something like
1
2
b d;
d.fn();
is compiled into something like
1
2
b d;
__a__fn(d);
And said function is like
1
2
3
4
__a__fn(b& x)
{
    __a__add(x);
}


virtual keyword changes how function is called to something like
1
2
3
4
__a__fn(b& x)
{
    x.__vtable[__add](x);
}
using saved information from virtual table to select correct function to call
yes i got it
thanks
Topic archived. No new replies allowed.