finicu
finicu

Reputation: 15

Polymorphism C++: field of base pointer not using value given by derived class constructor

I'm running into an issue with this code (it's a simplified version from a personal project):

#include <iostream>

class Piece
{
public:
    Piece() : art('=') {};

    char art;
};

class Pawn : public Piece
{
public:
    Pawn() : art('p') {};

    char art;
};

int main()
{
    Piece* piece = new Pawn; // piece->art should be 'p'
    std::cout << piece->art; // =
    
    return 0;   
}

In my project I'm trying to have an array of pieces of different types, which I was planning to do using Piece* objects. However, when I call the constructor for Pawn (or any other derived object) it seems like the base constructor is called instead.

Furthermore,

class Piece
{
public:
    Piece() : art('=') {};

    char art;
};

class Pawn : public Piece
{
public:
    Pawn() : art('p') {};
};

is apparently illegal, as Pawn does not have an art field, although it should inherit that from the base class!

Could someone enlighten me? How can I make it such that the constructor of the derived class is called instead? How can I get an array (vector) of Piece objects, which can be either Pawn, or other derived objects?

Upvotes: 1

Views: 62

Answers (1)

cigien
cigien

Reputation: 60228

You need to call the base class constructor like this:

class Pawn : public Piece
{
public:
    Pawn() : Piece('p') {}
         //  ^^^^^ not 'art'
};

See the reference for member initializer lists, which explains how this works.


If you have a std::vector<Piece*> it can store pointers to objects to derived types, such as Pawn*.

Upvotes: 2

Related Questions