Problem with Composition in C++

Changing from inheritance to composition

Page 1 of 1

1 Replies - 3374 Views - Last Post: 07 February 2009 - 07:13 AM Rate Topic: -----

#1 Scorpiobuzz  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 66
  • Joined: 06-February 09

Problem with Composition in C++

Post icon  Posted 06 February 2009 - 09:46 PM

Below are the two class that I have written so far. I was originally having the Controller class use the public inheritance of the menu class - worked beautifully. I want to change it to composition along with some other classes, being that it is the controller and I just can't seem to wrap my head around how you do that. I understant you initiate an object of the class you want to comp but how do you use all the functionality of that class like I was able to with inheritance. I need a clear, easy to understand answer, I have googled it a million times and still just can't understand how to make it work like inheritance does.


//This is the menu class:
class menu {
string name; //Private variables of class
string choices[5]; //Private variable array

string getName() const; //Public functions of the class, getters and setters
void setMenuName(string n);
string getChoice1() const;
string getChoice2() const;
string getChoice3() const;
string getChoice4() const;
void setChoices(string a, string b, string c, string d); //Function for string array variable
void print();
menu(string a, string b, string c, string d);

//This works fine, does everything I ask it to. :)

Here is the second class that I want to get the menu class into using composition. I originally had this class working with the menu class via a public inheritance of menu. All I want is the same operation via composition.

#include "Menu.h"
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

class Controller
menu cMenu;
void Start();



// This is the start function that used to work, when I was using inheritance:

void Controller::Start()
Controller::setChoices("Play Hangman", "Edit Random List", "Check Score", "Exit");

Is This A Good Question/Topic? 0
  • +

Replies To: Problem with Composition in C++

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6219
  • View blog
  • Posts: 23,965
  • Joined: 23-August 08

Re: Problem with Composition in C++

Posted 07 February 2009 - 07:13 AM

You should fix your code didn't close them.

You want to refer to the instance variable of the menu class, which you've declared as cMenu, like this:
void Controller::Start()
    cMenu.setChoices("Play Hangman", "Edit Random List", "Check Score", "Exit");

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1