Program creates object without my authorization

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.

main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include "foo.h"
#include "bar.h"

using namespace std;

int main()
{
    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;

    int menu;
    cin >> menu;

    if(menu == 1)
        Foo qux // Create a new object 'qux' from the class 'Foo'
    else
        cout << "Program exit." << endl;
}


foo.h
1
2
3
4
5
6
7
8
9
10
#ifndef FOO_H
#define FOO_H

class Foo
{
    public:
        Foo();    // constructor
};

#endif  // FOO_H 


foo.cpp
1
2
3
4
5
6
7
#include <iostream>
#include "konto.h"

Foo::Foo()
{
    std::cout << "Constructor created object Foo.\n";
}


bar.h
1
2
3
4
5
6
7
8
9
10
#ifndef BAR_H
#define BAR_H

class Bar : public Foo
{
    public:
        Bar();    // constructor
};

#endif  // BAR_H 


bar.cpp
1
2
3
4
5
6
7
#include <iostream>
#include "bar.h"

Bar::Bar()
{
    std::cout << "Constructor created object Bar.\n";
}


Console output

Program started at int main
Constructor created object Foo.
Constructor created object Bar.
Create an object from class Foo by pressing 1.
Press any other button to exit program.


The problem is the program should NOT create an object called Foo, its supposed to be created by the class Bar and sent to a vector(not in my example). Is the inheritance set up wrong?

Cant figure this one out on my own... any help would be great!
Bump! Anyone...?
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.

http://www.cplusplus.com/doc/tutorial/classes/


Is the inheritance set up wrong?


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.

Hope all goes well :)
Thank you and thanks a lot for the great explanation of the three relationships. Great link to :)
Topic archived. No new replies allowed.