let say i have a class A (base)

class B , C, D also inherit A [ multiple ]

then class E inherit class B, C, D... But class E also want to inherit class A [ multilevel ]

*I want to use class A protected function in class E...

But I encounter error during compile : reference to 'func in class A' is ambiguous..

Recommended Answers

All 5 Replies

You mean something like this? If you run this program you will see that class A is common to all the other classes. There are not separate instances of class A in class B, C and E. Any changes to the data in class A is reflected in all other classes because of the virtual keyword.

#include <iostream>
using std::cout;

class A
{
public:
    A() {x = 0;}
    void show() {cout << "x = " << x << '\n';}
protected:
    int x;
};

class B :virtual public A
{
public:
    B() {y = 0; A::x = 2;}
    void show() {cout << "y = " << y << '\n'; A::show();}
protected: 
    int y ;
};

class C :virtual public A
{
public:
    C() {z = 0; A::x = 3;}
    void show() {cout << "z = " << z << '\n'; A::show();}
protected: 
    int z ;
};
class E : virtual public B,virtual public C, virtual public A
{
public:
    E() { A::x = 4; B::y = 2;}
    void show()
    {
        B::show();
        C::show();
        A::show();
    }
};

int main()
{
    E e;
    e.show();    
}

Hmm... I didn't use virtual and didn't redeclare base function(show) in my child class...

It's like:

class A
    {
    protected:
    	int convert(char a) { return a-48; }
    };

    class B : public A
    {
    protected:
    	int cal_circle(char radius) { return 3 * convert(radius); }
    };

    class C : public A
    {

    protected:
    	int cal_square(char width) { return convert(width)*2; }
    };
    class E :  public B, public C,  public A
    {
    public:
    	void size ()
    	{
			cout<<"circle size: "<<cal_circle('3')<<endl;
			cout<<"square size: "<<cal_square('2')<<endl;
			//at here i need to use A.convert(int *)
			cout<<"convert: "<<convert('4')<<endl;
    	}
    };

    int main()
    {
    E e;
    e.size();
    }

I just tried to use virtual and it solve the error but why?

Compile and run the program I posted but remove the virtual keyword everywhere. It will show you the difference between using virtual and not using virtual.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.