Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Inheritance Exercise

      Class One : public Two
        {
        public:
           One()
           {
              Three three;
              cout << "something";
           }
        private:
           Four _four;
       };

I have to display a sentence: "One Two Three Four Five Six Seven" and class One have to remain as it is. Every class can't display more than one word in her constructor and destructor.

So... i've figured out that my base class is Class Four. I've also made constr. & destr. in every class and tried to write something in their bodies but thats what ive got on output:

Class Four Constructor:
Class Three Constructor:
Class Two Constructor:
Class Four Constructor:
Class Four Constructor:
Class Three Constructor:
Class One Constructor:
Class Three Destructor:
Class Four Destructor:

DESTRUCTION:
Class One Destructor:
Class Four Destructor:
Class Two Destructor:
Class Three Destructor:
Class Four Destructor:

my main function:

int main()
{
 One one; //<----  it also have to remain
 cout << endl;
 cout << "DESTRUCTION:\n";
}

I've read a few articles about inheritance but still have no idea how to display words in classes constr. & destructors but dont do it twice or more even if i create objects of these classes like it is done in class One.

P.S Sorry for gramma and other mistakes ;)

like image 664
mctl87 Avatar asked Dec 07 '25 09:12

mctl87


1 Answers

What we can deduce, based solely on the known definition of One (and my remembrance of C++ construction rules, which may not be 100% accurate :-), not taking into account any additional possible inheritance relationships between the classes:

  1. the output of Two() (being the base class constructor) comes before the output of all other constructors,
  2. the output of Four() (belonging to a member of the derived class) comes next,
  3. then the output of Three() (a local object within the One() constructor),
  4. then the output of One() itself,
  5. then the output of ~Three() (being a local variable, it goes out of scope when returning from One()).

And here we have our shiny One object constructed. Since there is not much we can do with it, let's destroy it! Note that all objects are destroyed exactly in the opposite of their order of construction; this is a fundamental C++ rule. Thus

  1. first comes the output of ~Four() (since members are destroyed before their owner),
  2. (then would come the output of the nonexistent ~One(), as the derived portion of the class is destroyed before its base part),
  3. then the output of ~Two() as the base part is destroyed last.

This gives you exactly seven possible numbers to output, thus you need no additional base classes or members anywhere. Just put the right numbers into the output of the right constructors & destructors :-)

like image 172
Péter Török Avatar answered Dec 09 '25 23:12

Péter Török