-1

I have the following classes:

class CPolygon
{
  SPolygon* data; // will be populated by constructor
  // ... members here ...
public:
  CPolygon();
  CPolygon(int type);
  SPolygon getData(int index);
  // ... methods here ...
};

class CSquare : public CPolygon
{
  // ... members here ...
public:
  CSquare();
  SSquare getData(int index);
  // ... methods here ...
};

The second CPolygon() constructor accepts the type of polygon you want.

Is there a way to call this (second) constructor on CSquare() constructor passing the value for square type, like:

CSquare::CSquare()
{
  CPolygon(TYPE_SQUARE);
}

to make data that are square?

EDIT

I added new member and method/function. This is the structure (and union):

union SPolygon
{
  SHead   head;
  SSquare square;
  // ... more structure here ...
}

struct SSquare
{
  SHead head;
  // ... more membere here ...
}

I want to return the square data:

SSquare CSquare::getData(int index)
{
  return getData(index).square;
}

But the getData() (inside the function) is considered as CSquare's but I need it to be CPolygon's. How?

ReignBough
  • 435
  • 4
  • 10

1 Answers1

4

You can use an member initialization list:

CSquare::CSquare(): CPolygon(TYPE_SQUARE) {}

This invokes CPolygon's constructor first, according to the correct type, then the CSquare() constructor body is executed.

Note: Initialization lists apply not only to super-classes, but also to ordinary class members. For examples, please refer to C++ Member Initialization List.

For your edited question, use CPolygon::getData to call the specified version of getData:

SSquare CSquare::getData(int index)
{
  return CPolygon::getData(index).square;
}
Community
  • 1
  • 1
Yang
  • 7,712
  • 9
  • 48
  • 65