A
A
Anderwonder2012-03-30 17:10:15
C++ / C#
Anderwonder, 2012-03-30 17:10:15

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)
       {
              КупитьКотэ();
       }
};

How can I make it so that the Son class constructor would call the GrandFather class constructor, but not the Father constructor?
So far, I did it this way: I added the Father constructor
Father(int Capital, int x):GrandFather(Capital){}
and the Son constructor did Son(int Capital):Father(Capital,1).
But I would like a solution without extra lines.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
R
rasa, 2012-03-30
@Anderwonder

The same question , however, about Java.

E
egorinsk, 2012-03-30
@egorinsk

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.

R
Rafael Osipov, 2012-03-30
@Rafael

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.

K
Konstantin Kitmanov, 2012-03-30
@k12th

Is it possible to do with aggregation instead of inheritance?

B
bogolt, 2012-03-30
@bogolt

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);

In general, in C++ it is impossible not to call a constructor when creating an object, you can only choose which of the constructors will be called.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question