Search This Blog

Sunday, 9 March 2014

Composition in C++


/*
Composition means using the object of one class in another without inheriting.
Example:
class Student
{
  //Codes
}
class Address
{
 Student s;
 ...// Codes
}
*/



#include<iostream.h>
#include<conio.h>

class Book
{
    private : int bCode;
              char *bName;
    public :
    void SetbCode(int n)
    {
      bCode=n;
    }
    void SetbName(char name[])
    {
        bName=name;
    }
    int GetbCode()
    {
        return bCode;
    }
    char* GetbName()
    {
        return bName;
    }
};
class Student
{
    public :
    int roll;
    char *name;
    Book bk;
    Student(int roll,char nick[],Book k)
    {
        this->roll=roll;
        name=nick;
        bk=k;
    }
    void showDetails()
    {
        cout<<"\nStudent name is : "<<name<<"  "<<roll;
        cout<<"\nBook details are : "<<bk.GetbName()<<"  "<<bk.GetbCode();
    }
};

void main()
{
       Book bt;
       bt.SetbCode(1007);
       bt.SetbName("MicroProcessor");
       Student s(21,"sanjay kumar singh",bt);
       s.showDetails();
       getch();
}

Output


No comments:

Popular Posts