I am writing a program to familiarize myself better with certain aspects of classes, and was wondering how to properly implement a class inside a class, and make it so only a certain instance of the original class can call a certain instance of the nested class. Basically I'm trying to get an object to have an object on it, and to make the second object exclusive to the first object. I'm confused about how to go about this.
Classes' Classes
Collapse
X
-
Something like this
[code=cpp]class Outer
{
private:
class Inner
{
private:
int data;
public:
int GetValue() const { return data; }
void SetValue(int newValue){ data = newValue; }
Inner(int init = 0) : data(init) {}
};
Inner *pInner;
public:
Outer(int init = 0) : pInner(new Inner(init)) {}
~Outer(){ delete pInner; }
int GetValue() const { return pInner->GetValue(); }
void SetValue(int newValue){ pInner->SetValue(newVa lue); }
};[/code]Although this is a slightly converluted way to store an int :D -
Originally posted by Ganon11[CODE=cpp]class yourFirstClass {
private:
class yourSecondClass {
// yourSecondClass definition here.
}
// yourFirstClass definition here
}[/CODE]
Follow this basic pattern, and you should be OK.Comment
-
Originally posted by newguy194I have one more problem, how can I have multiple private classes inside my outer class? like Inner1 and Inner2, I do not fully understand how this works.
Code:#include <cstdlib> #include <iostream> using namespace std; class Food { private: class vegetable { private: string vegname; int calories; public: int GetCalories() const { return calories; } void SetCalories(int newValue){ calories = newValue; } vegetable(int init = 0) : calories(init) {} }; class fruit { private: string fruitname; int calories; public: int GetCalories() const { return calories; } void SetCalories(int newValue){ calories = newValue; } fruit(int inita = 1) : calories(inita) {} }; vegetable *newveg; fruit *newfruit; public: Food(int init = 0) : newveg(new vegetable(init)) {} ~Food(){ delete newveg; } int GetCaloriesveg() const { return newveg->GetCalories(); } void SetCaloriesveg(int newValue){ newveg->SetCalories(newValue); } }; int main(int argc, char *argv[]) { Food(carrot); carrot.SetCaloriesveg(50); cout<<carrot.GetCaloriesveg()<<"\n"; system("PAUSE"); return EXIT_SUCCESS; }
Comment
-
Originally posted by Banfa[code=cpp]
Food(int veginit = 0, int fruitinit = 0)
: newveg(new vegetable(vegin it)),
newfruit(new fruit(fruitinit ))
{
}
~Food()
{
delete newveg;
delete newfruit;
}
[/code]Comment
Comment