Could anybody point me in the direction of a good tutorial/example of composition being used. I am having some trouble implementing it in a project. Specifically, where it occurs within a class, the header and .cpp file. Thanks
Printable View
Could anybody point me in the direction of a good tutorial/example of composition being used. I am having some trouble implementing it in a project. Specifically, where it occurs within a class, the header and .cpp file. Thanks
Here is an example of composition. The class ComposedOfInt is composed of an int. If you're talking about what I think you are talking about, then composition is just the use of a type as a member of a new class. Often, composition is preferred to inheritance when extending the interface of an existing class. If this is not what you are talking about, maybe give a little more information.Code:class ComposedOfInt
{
public:
explicit ComposedOfInt(int data = 0) : data_(data) { }
int getData() { return data_; }
void setData(int data) { data_ = data; }
private:
int data_;
};
#include <iostream>
int main()
{
ComposedOfInt coi(3);
std::cout << coi.getData() << std::endl;
coi.setData(coi.getData() + 2);
std::cout << coi.getData() << std::endl;
}
Hmm I think you meant to put:
;)Code:class ComposedOfInt
{
public:
explicit ComposedOfInt(int data = 0) : data_(data) { }
int getInt() { return data_; }
void setInt(int data) { data_ = data; }
private:
int data_;
};
The only reference I have heard to composition in C++ is defining a class within another. But that only once.
Explain more what you are trying to do and what trouble you are having.