-3

I have confusion about how to use composition with inheritance. I have written a simple example based on my understanding. Kindly help me.
1) if the above code is correct or not ? 2) is my multiple inheritance implementation correct ? 3) I am doing both inheritance and composition in Employees class. Is that correct ?

class address
{
private:

public:

    struct MyStruct
    {
        int houseno;
        string colony;
        string city;    
    };

    MyStruct m;
    //shows the address
    void get_address()
    {
        cout << m.houseno;
        cout<<m.colony;
        cout << m.city;
    }
};
class telephoneNo
{
private:
    string c;
public:

    // takes the telephoneNo of the employee from user and pass to local variable
    void set_telephone(string d)
    {
        c = d;
    }
    void get_telephone()
    {
        cout << c;
    }
};
//multiple level inheritance
class employee :public address, public telephoneNo  
{
    private:
        string name;
    public:
    address obj;       //composition
    telephoneNo obj2;  // composition

    void employee_name(string a)
    {
        name = a;
    }
    void show_emplyeeDetail()
    {
        cout << "Employee's Name is: ";
        cout << name<<endl;
        cout << "Employee's Address is: ";
        obj.get_address();
        cout<<endl;
        cout << "Employee's Telephnoe no is: ";
        obj2.get_telephone();
        cout<< endl;
    }
};
void main()
{

emp.obj; 
    cout << "Enter Name of employee " << endl;
    cin >> nameInput;
    cout << "-----------Enter address of employee----------- "<<endl;
    cout << "Enter house: ";
    cin >> emp.obj.m.houseno;  //passing parameters to the struct
    cout << "Enter colony : ";
    cin >> emp.obj.m.colony;   
    cout << "Enter city: ";
    cin >> emp.obj.m.city;
    cout << "Enter telephone of employee: ";
    cin >> telephoneInput;

    emp.employee_name(nameInput);
    emp.obj2.set_telephone(telephoneInput);
    cout << "-------------Employee's Details are as follows------------ " << endl;
    emp.show_emplyeeDetail();
}
ambiguous
  • 1
  • 2

1 Answers1

0

Your employee "is" an address and a telephone number - that's multiple inheritance

class employee :public address, public telephoneNo 

In main you can access for any employee the public fields and methods of both base classed, e.g.

employee employee1; 
employee1.get_address();

On the other side the employee "has" an address and a telephone number - that's composition.

employee1.obj.get_address();

Beware, the two addresses and telephone numbers of your employee are strictly separated and can (will) contain different content.

But best recommendation is to start with a good beginners book on C++.

milbrandt
  • 1,438
  • 2
  • 15
  • 20