Home > DeveloperSection > Forums > How to make a virtual function in C Plus Plus?
Hank Greenberg
Hank Greenberg

Total Post:12

Points:84
Posted on    June-13-2013 7:47 AM

 Visual C++ Visual C++ 
Ratings:


 1 Reply(s)
 748  View(s)
Rate this:
Hi Expert,

How to make a virtual function in c++?
Please provide line of code.

Thanks in advance. 


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    June-14-2013 1:57 AM

try this:

Example of Virtual function:
class base{
public:
 int i;
base(int x){ i=x; }
virtual void func()
{
cout<<"Using bse version of func(): ";
cout<< i<<'\n';
}
};

class derived1:public base{
public:
void func()
{
cout<<"Using derived1's version of func(): ";
cout<<i*i<<'\n';
}
};

class derived2:public base{
public:
derived2(int x):base(x){}
void func()
{
cout<<"Using derived2's version of func(): ";
cout<<i+i<<'\n';
}
};


int main()
{
base *p;
base ob(10);
derived1 d_ob1(10);
derived2 d_ob2(10);
p=&ob;
p->func();
p=&d_ob1;
p->func();
p=&d_ob2;
p->func();
return 0;
}

Don't want to miss updates? Please click the below button!

Follow MindStick