Problem with Composition in C++

Changing from inheritance to composition

Page 1 of 1

1 Replies - 3123 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.

[code]

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

public:
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();
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.

#ifndef CONTROLLER_H
#define CONTROLLER_H
#include "Menu.h"
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

class Controller
{
public:
menu cMenu;
void Start();
Controller();

private:

};

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

void Controller::Start()
{
Controller::setMenuName("MENU");
Controller::setChoices("Play Hangman", "Edit Random List", "Check Score", "Exit");
menu::print();
}

Is This A Good Question/Topic? 0
  • +

Replies To: Problem with Composition in C++

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6107
  • View blog
  • Posts: 23,663
  • Joined: 23-August 08

Re: Problem with Composition in C++

Posted 07 February 2009 - 07:13 AM

You should fix your code tags...you 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.setMenuName("MENU");
    cMenu.setChoices("Play Hangman", "Edit Random List", "Check Score", "Exit");
    cMenu.print();
}

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1