virtual ineritance
Nov 3, 2015 at 10:30pm UTC
Hi everyone!
i have a question- when i write: Base* b=new Multiple(); b->print();
why does Base::print() activated, and not Multuple::print()?
print is virtual function..
thanks for help !
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
class Base
{
public :
virtual void print(){}
};
class DerivedOne: virtual public Base
{
public :
void print() const {cout << "DerivedOne\n" ;}
};
class DerivedTwo :virtual public Base
{
public :
void print() const {cout << "DerivedTwo\n" ;}
};
class Multiple : public DerivedOne, public DerivedTwo
{
public :
void print() const {DerivedTwo :: print();}
void g(){cout<<"blabla" ;}
};
Last edited on Nov 3, 2015 at 10:31pm UTC
Nov 4, 2015 at 12:00am UTC
1 2 3 4 5
class Base
{
public :
virtual void print() { }
};
The base classes print method needs to be const
virtual void print() const { }
Also you can make use of the override keyword which gives an error when your method fails to override a base class method.
Example
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>
using namespace std;
class Base
{
public :
virtual void print() {}
};
class DerivedOne: virtual public Base
{
public :
void print() const {cout << "DerivedOne\n" ;}
};
class DerivedTwo :virtual public Base
{
public :
void print() const {cout << "DerivedTwo\n" ;}
};
class Multiple : public DerivedOne, public DerivedTwo
{
public :
void print() const override {DerivedTwo::print();}
void g(){cout<<"blabla" ;}
};
Nov 4, 2015 at 4:09am UTC
thanks, but this code was written like this on purpose.
can you explain again why Base::print is called? even thogh print is virtual..?
Topic archived. No new replies allowed.