assign one class object to another class object in c++
Asked Answered
R

2

3

I want to assign one class object to another class object in c++.

Ex: There is one class Dog and another class Cat. Create one one instance of each (d1 & c1). Don't want to use any STL. I want to use this statement in my code

d1 = c1;

Program

class dog
{
    char  dc;
    float df;
    int   di;   
public:
    void setdata2(char c, float f, int i)
    {   dc = c; df = f; di = i; }
    void showdata2()
    {   cout  <<"char =" << dc <<", float =" << df <<", int =" << di  <<endl;   }
};


class cat
{
    float cf;
    int ci;
    char cc;    
public:
    void setdata(float f, int i, char c)
    {   cf = f; ci = i; cc = c; }
    void showdata()
    {   cout <<"float =" << cf <<", int =" << ci <<", char =" << cc  <<endl;    }
};


int main()
{
    dog d1, d2;
    cat c1, c2;

    d1.setdata2('A', 56.78, 30);
    c1.setdata(12.34, 2, 3);
    d1.showdata2();
    c1.showdata();

    d2 = c1;        // Question 1

    dog d3(c1);     // Question 2

    dog d4 = c1;    // Question 3

    return 0;
}

Please answer Question 1/2/3 each separately.

Risibility answered 17/9, 2016 at 15:39 Comment(0)
R
3

I want to assign one class object to another class object in c++.

It is possible to assign an object of type A to an object of type B if A is implicitly convertible to B, and B is assignable - or, if B has an overloaded assignment operator that accepts objects of type A.

There are two ways to define a conversion from a custom type A to an unrelated type B. You can either define a conversion function for A, or you can define a converting constructor for type B.

1) This is copy assignment. The above explanation applies. Either define cat::operator dog() or dog::dog(cat) or dog::operator=(cat).

2) This is direct initialization. It is not an assignment which is what you asked about. Defining an implicit conversion works for this as well, but an overloaded assignment operator will not. However, an overloaded constructor would be a substitute third alternative.

3) Even though this looks a bit like assignment syntactically, this is actually copy initialization. Same rules apply as 2).


PS. Note that you're defining two variables by the name d3. That is an error.

Robot answered 17/9, 2016 at 16:52 Comment(2)
Can you tel me in which order compiler search for definition in your 1st answer.Risibility
it is not working. @user2079303 Code LinkRisibility
D
2

You can't assign two objects of different classes to each other which are not related to each other until you overload "=" operator for them.

You can read about operator overloading here

Dossier answered 17/9, 2016 at 15:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.