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
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; }
Last edited by jlou; 10-25-2004 at 09:55 PM. Reason: Thanks JaWiB! :oops:
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_; };
"Think not but that I know these things; or think
I know them not: not therefore am I short
Of knowing what I ought."
-John Milton, Paradise Regained (1671)
"Work hard and it might happen."
-XSquared
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.
The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.