In: Computer Science
Step1 - Define two classes, Whole and part. Use a strong "has a" relationship with the two classes.
Constructor Functions
Define a default constructor for the Part class.
Default just prints out "In default part constructor"
Define a default and a parm constructor for the Whole class.
In Whole Default constructor assigns wholeName = "None"; and prints out "In whole default Constructor"
In Whole Parm constructor - Passes in name to WholeName and
Then It prints out value of wholeName variable and "In Whole parm constructor"
Destructor Functions
Define a destructor function for the part class.
Define a string variable called wholeName in the whole class.
Define a getName function for whole class.
Two test.
Step 2 - Declare a Whole W1, with default constructor
Have the Whole constructor print "called default constructor", and contents of wholeName variable
Have the Whole Destructor print "called destructor", and contents of wholeName variable
Declare a Whole W2, with a parm constructor - Have it pass in "w2"
Have the Whole constructor print "called parm constructor", and contents of wholeName variable.
Have the Whole Destructor print "called destructor", and the contents of wholeName variable.
Step 3 - use the dot
Use the dot notation to print out the contents of W1 wholeName variable
Use the dot notation to print the contents of W2 wholeName variable
HAS-A Relationship:
Basically the term Composition reffers to the HAS-A Relationship i.e the use of instance variables that are references to the other objects.
In our code snippet we have declared HAS-A Relationship as : class Part: public Whole
Find below code for the above scenario:
Code;
#include <iostream>
using namespace std;
class Whole{ // Whole Class defination
public:
string wholeName;
void getName(){ //getName function for whole
class.
}
Whole(){ //Default constructor of a Whole
class
string wholeName="None"; //Default constructor Assignmnt to
the wholeName variable
cout<<"In whole default Constructor\n";
}
Whole(string wholeName){ //Parm constructor of a Whole
class
cout<<wholeName;
cout<<"In Whole parm constructor\n";
}
~Whole(){ //Destructor function
cout<<"called destructor\n";
cout<<wholeName;
}
};
class Part: public Whole{ //Has-A Relationship
implementation
public:
Part(){ //Default constructor of a Part
class
cout<< "In default part constructor";
}
~Part(){ //Destructor function
}
};
int main()
{
Whole W1("called default constructor\n");
cout<<W1.wholeName; // dot notation to
print out the contents of W1
Whole W2("Called parm constructor\n");
cout<<W2.wholeName; // dot notation to print out the
contents of W2
return 0;
}
Code Snapshots with output:
I hope you find this helpful if not please comment below i will help you.
Thanks, Do not forget to upvote the answer!!
Happy Learning!! :)