Constructor with a virtual function call in C ++

Possible duplicate:
Calling virtual functions inside constructors

first of all, below the code does not work visual C ++, but works with bloodshed

the output is 0, but acc. it will be 1 to me; 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;
    }
    double area()const {return 1.0;}
    void print() const
    {
        cout<<"\nPoint\n";
        cout<<x<<"\t"<<y;
    }
};

int main()
{   
    point p(1,2);
    return 0;
}
+3
source share
4 answers

There is a subtle flaw in your code:

double area()const {return 1.0;}

The base class method is area()not declared const. point :: area is therefore not a virtual method. Either declare shape::area constit or remove const from point::area, and it will work as expected.

+3
source

- . (. ) .

+2

, . , ++

, , , "initialize", , , , .

0

You got the correct result. It should be 0. When you call area()in the constructor of your derived class, in fact, instead of the original version, the base version is area()called. A call to a virtual function inside the constructor will not call overriding functions in derived classes.

Read this.

-2
source

Source: https://habr.com/ru/post/1727144/


All Articles