virtual & override


When I call a variable of type TObject and initialize it with TLine and call
override method draw() it calls TObjects draw() method not TLine's ???

can somebody tell me why?



#include <Windows.h>
#include <vector>
#include <GL\GL.h>
#include <GL\GLU.h>
#include "GL\glut.h"

#pragma comment(lib,"gle.lib")
#pragma comment(lib,"glut32.lib")
#pragma comment(lib,"opengl32.lib")





struct TPoint
{
public:
TPoint(){};
TPoint(float x,float y,float z)
{
this->x = x;
this->y = y;
this->z = z;
};

float x;
float y;
float z;

};

class TObject

{
private:
public:
TObject() {};
~TObject() {};
public : virtual void draw() {};
};

class TLine : public TObject
{
private:
TPoint *sPt;
TPoint *ePt;
public:
TLine(TPoint *sPt,TPoint *ePt) {this->sPt = sPt; this->ePt = ePt ;};
~TLine() {};
public: virtual void draw() override;
};

class TGroup
{
private:
static std::vector<TObject> *objects;
public:
TGroup();
~TGroup() {};
void AddObject(TObject *Obj);
static void draw(void);
static void resize(int x,int y);
void StartGL();
};

void TLine::draw()
{
glBegin(GL_POLYGON);
glColor3f(0,0,1);
glVertex3f(sPt->x,sPt->y,sPt->z);
glVertex3f(ePt->x,ePt->y,ePt->z);
glEnd();
};

void TGroup::draw(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0,1.0,1.0);

glLoadIdentity();
//glMatrixMode(GL_PROJECTION);
gluLookAt(0.0,0.0,5.0,0.0,0.0,0.0,0.0,1.0,0.0);
glScalef(1.0,2.0,1.0);


for (int i=0; i<objects->capacity();i++)
{
objects->at(i).draw();
};

glFlush();

};

TGroup::TGroup()
{
int argc = 1;
char *argv[1] = {(char*)"NANOCAD"};
glutInit(&argc,argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500,500);
glutInitWindowPosition (100, 100);
glutCreateWindow(*argv);
glClearColor(0,0,0,0);
glShadeModel(GL_FLAT);
glutDisplayFunc(draw);
glutReshapeFunc(resize);

};

void TGroup::resize(int x , int y)
{
glViewport(0,0,(GLsizei) x, (GLsizei) y);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-1.0,1.0,-1.0,1.0,1.5,20.0);
glMatrixMode(GL_MODELVIEW);
};

void TGroup::AddObject(TObject *Obj)
{
objects->push_back(*Obj);
};

void TGroup::StartGL()
{
glutMainLoop();
};

std::vector<TObject>* TGroup::objects = new std::vector<TObject>();



You can achieve the polymorphic behavior only with (smart) pointer.

If you copy a derived object to a base object (like here objects->push_back(*Obj);) only the base object data (if any) is copied.
Topic archived. No new replies allowed.