0

I wrote two classes- Polygon and Rectangle. in both of them, I wrote a constructor which asks the user for the points of the polygon. I expected an override at read method- but it didn't occur. this is the code:

Polygon.h:

#ifndef __POLYGON_H
#define __POLYGON_H

#include "Point.h"
#include <vector>
#include <string>
class Polygon {
public:
    Polygon();
    Polygon(int c);

protected:
    virtual std::vector<Point*> read();

private:
    const int color;
    std::string type;
    std::vector<Point*> _points;
};

Polygon.cpp:

#include "Point.h"
#include "Polygon.h"
#include <iostream>

using std::cout;
using std::endl;
using std::vector;
using std::cin;

Polygon::Polygon():
color(-1)
{}

Polygon::Polygon(int c):
color(c),
type("polygon"),
_points(this->read()) //******the problem is here*******
{
}

std::vector<Point*> Polygon:: read(){
    int x,y=0;
    vector<Point*> temp;
    cout<<"enter new x value and y value for point. enter '!' for finishing"<<endl;
    while (std::cin>>x && cin>>y){
        Point* p=new Point(x,y);
        temp.push_back(p);
        cout<<"enter new x value and y value for point. enter '!' for finishing"<<endl;
    }
    return temp;
}

Rectangle.h:

#ifndef RECTANGLE_H
#define RECTANGLE_H

#include "Point.h"
#include "Polygon.h"

class Rectangle: public Polygon
{
    public:
        Rectangle(int c);
        virtual std::string getType();
    protected:
        virtual std::vector<Point*> read();
    private:
        Rectangle();
};

#endif 

Rectangle.cpp:

#include "Rectangle.h"
#include "Point.h"
#include "Polygon.h"
#include<vector>
#include<iostream>

using namespace std;

Rectangle::Rectangle(int c):
    Polygon(c)
{
}
std::vector<Point*> Rectangle:: read()
{
    int x,y=0;
    std::vector<Point*> temp;
    cout<<"enter 4 rectangle valid points"<<endl;
    for (int i=1; i<5; i++){
        cout<<"enter new x value and y value for point "<< i << ". enter '!' for finishing"<<endl;
        std::cin>>x;
        std::cin>>y;
        Point* p=new Point(x,y);
        temp.push_back(p);
    }
    return temp;
}

Now, when i write this code at main:

Polygon* r1=new Rectangle(1);

I get the line: enter new x value and y value for point. enter '!' for finishing- from the Polygon's read method, insted of Rectangle as I expected.

why there is no override at read method? I also tried wrriting override in read method at Rectangle, and it stays the same.

Rodrigo
  • 167
  • 2
  • 9
  • In short, virtual calls in constructors and destructors don't do what you expect. The derived class isn't yet constructed when the base class constructor runs, so its methods can't be called. – Mat Nov 14 '15 at 16:48
  • Duplicate of http://stackoverflow.com/q/962132 and http://stackoverflow.com/q/496440. – Kerrek SB Nov 14 '15 at 16:48

0 Answers0