> Virtual function in c++?

Virtual function in c++?

Posted at: 2014-12-18 
Your statement is wrong. You can - as the following code shows - call the base class method ...

#include

using namespace std;

class B

{

public:

virtual void display()

{ cout<<"Content of base class.\n"; }

};

class D1 : public B

{

public:

void display()

{ cout<<"Content of derived class D1.\n"; }

};

class D2 : public B

{

public:

void display()

{ cout<<"Content of derived class D2.\n"; }

};

int main()

{

D1 d1;

D2 d2;

B b;

B *ptr[] = {&d1, &d2, &b};

ptr[0]->display();

ptr[1]->display();

ptr[2]->display();

}

Maybe you are referring to a pure virtual function scenario, which enforces that derived classes implement the pure virtual function of the base class. The following example won't compile, because D3 (derived from B does not implement the display method:

#include

using namespace std;

class B

{

public:

virtual void display() = 0;

};

class D1 : public B

{

public:

void display()

{ cout<<"Content of derived class D1.\n"; }

};

class D2 : public B

{

public:

void display()

{ cout<<"Content of derived class D2.\n"; }

};

class D3 : public B

{

public:

void display11111()

{ cout<<"Content of derived class D3.\n"; }

};

int main()

{

D1 d1;

D2 d2;

D3 d3;

// B b; // error: cannot declare variable ‘b’ to be of abstract type ‘B’

// B b;

B *ptr[] = {&d1, &d2, &d3};

ptr[0]->display();

ptr[1]->display();

ptr[2]->display();

}

I hope this helps

i was wondering about use of virtual functions in c++.If we were to declare a function in base class as virtual,then we cannot call that function.so if we dont want to call it,why define it in the first place?

we could just define functions in different derived classes with same names and call them with their associated objects.

someone please explain to me the need for virtual functions....with an eg. if you could.