constructor with virtual function call in c++
first of all below code is not working visual c++ , but workin with bloodshed
output is 0 , but acc. to me it shud be 1 ; can anyone explain this
#include<iostream>
using namespace std;
class shape
{
public:
virtual void print() const =0;
virtual double area() { return 0.0;}
};
class point : public shape
{
int x;
int y;
public :
point(int a=11, int b=11)
{
x=a;
shape *s;
s=this;
cout<<s->area();
y=b;
}
doubl开发者_运维百科e area()const {return 1.0;}
void print() const
{
cout<<"\nPoint\n";
cout<<x<<"\t"<<y;
}
};
int main()
{
point p(1,2);
return 0;
}
There's a subtle flaw in your code:
double area()const {return 1.0;}
The base class' area()
method is not declared const
. point::area is therefore not a virtual method. Either declare shape::area
const
as well or remove const from point::area
and it will work as expected.
Calling virtual functions from the constructor is a really bad idea. See this Calling virtual functions from constructor (see 3rd para) for details.
Calling a virtual function in the constructor of a function acts as if the function is not virtual. It can be confusing, but it's standard behavour in c++
If you want to achieve your aim then you should probably have an "initialise" function that you call after the constructor in which virtual function calls will work as you expect.
You got the correct output. It should be 0
. When you call area()
in the constructor of your derived class, actually the base version of area()
is called instead of the derived version. Calling a virtual function inside a constructor won't call the overriding functions in the derived classes.
Read this.
精彩评论