简体   繁体   中英

Constructor of derived class calling constructor of base class

In the following code, when I try to create an object of Obiektstatyczny , the constructor of Miasto (base class) is being called.

class Miasto
{
    public:
    Miasto();
    int rozmiar;
};


class Obiektstatyczny :public Miasto
{
    std::vector <Obiektstatyczny> blokowisko;
    int x, y;
public: 
    Obiektstatyczny();
};


Obiektstatyczny::Obiektstatyczny()
{
    for (int i = 2; i < rozmiar; i++)
        for (int j = 2; j < rozmiar; j++)
            blokowisko.push_back(Blok(i, j));
}

Miasto::Miasto()
{
    cin >> iloscBlokow;
    cin >> szerokoscBloku;
    rozmiar = iloscBlokow*szerokoscBloku;

    mapa.assign(rozmiar, vector<int>(rozmiar));
    bufor.assign(rozmiar, vector<int>(rozmiar));

    for (int i = 0; i<rozmiar; i++)
        for (int j = 0; j < rozmiar; j++)
            mapa[i][j]=bufor[i][j]=0;
}

I think the reason is that I was trying to create the new Obiektstatyczny object by itself, not through the base class, thus the program kept repeating itself. However, I don't know a way to do this properly. My attempts to do this failed miserably.

I tried to create a field inside the Miasto class containing Obiektstatyczny , and then initializing it in a method of Miasto , but i got "unknown override specifier" error.

Obiektstatyczny obj;
void initializeObj()
    {
        obj = Obiektstatyczny();
    }

What you have is this:

struct X
{
    std::vector<X> stuff;
    X();
}

That is, an object contains a list of objects of the same type. This is not an immediate problem, but you need to be careful with such code.

If you create a non-empty list in the constructor

X::X()
{
    stuff.push_back(X());
    stuff.push_back(X());
    stuff.push_back(X());
    stuff.push_back(X());
}

this creates a logical error: to make an object, you need to make 4 objects; to make each of these objects, you need to make 4 other objects, ...

If the constructor doesn't fill the vector with actual objects, and leaves it empty, no immediate problem will occur. So you might want to move your code that generates a non-empty list into a separate function, eh init() . Or a separate constructor:

X::X()
{
    // leave stuff empty
}

X::X(size_t size)
{
    for (size_t i = 0; i < size; ++i)
        stuff.push_back(X()); // each of the created objects has empty stuff
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM