I want this to create an object and give me a menu, when I select 1, its supposed to create an other object from another class. But it creates both objects as soon as I run the program, and I dont know why.
cout << "Program started at int main" << endl;
Bar baz; // Create a new object 'baz' from the class 'Bar'
cout << "Create an object from class Foo by pressing 1." << endl
<< "Press any other button to exit program." << endl;
cin >> menu;
if(menu == 1)
Foo qux // Create a new object 'qux' from the class 'Foo'
cout << "Program exit." << endl;
The problem is the program should NOT create an object called Foo
Foo is created because of this:
class Bar : public Foo
When you create a derived class object, the base class constructor is called, then the derived constructor. This is done so the base class can initialise it's member variables which may be needed by the derived class. Even so, you still just have the 1 derived object.
It is hard to say from this example, but sometimes inheritance is not warranted.
There are 3 relationships with classes:
1: "IS A" implies inheritance - An Orange is a type of Fruit .
2: "HAS A" implies composition or aggregation - A circle has a centre point
3: "USES A" A class takes an object as an argument - A Circle can be created from 3 points
Composition is preferred over inheritance where possible.