Answer the question
In order to leave comments, you need to log in
Is it possible to call the grandparent constructor bypassing the parent constructor?
There are 3 classes:
class GrandFather {
public:
GrandFather(int Capital)
{
ПостроитьДом();
}
};
class Father:public GrandFather{
public:
Father(int Capital):GrandFather(Capital)
{
КупитьСобаку();
}
};
class Son:public Father{
public:
Son(int Capital):Father(Capital)
{
КупитьКотэ();
}
};
Answer the question
In order to leave comments, you need to log in
A constructor is supposed to be used to initialize fields of a class, such as those that are dynamic objects. In this case, it turns out a strange thing, we have a field (in the parent), but its initialization code is not called. This is not true.
Business logic should not be placed in the constructor, the "BuyDog" function should be moved out of the constructor to a place specially designed for this. Thus, the problem will be solved by itself.
There is such an old rule that if it becomes necessary to write ugly code, then a mistake has been made in the design. If there is a need for such a constructor call as you described, then it is worth reconsidering the organization of the class hierarchy.
Is it possible to do with aggregation instead of inheritance?
Make two Father constructors, one that buys the dog and one that doesn't, and call the one you need. Well, or as you yourself suggested, you can pass an attribute indicating the need for this action
Father(int capital, bool need_to_buy_god);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question