문제

    #include<iostream>

    using namespace std;

    class base
    {
    int i;
    public:
    base()
    {
    i=10;
    cout<<"Base Constructor\n";
    }
    base(base &a)
    {
    cout<<"base Copy Constructor\n";
    a.i=i;

    }

    ~base()
    {
    cout<<"base Destructor\n";
    cout<<i<<endl;
    }

    };

    class derived:public base
    {
    int j;
    public:
    derived()
    {
    j=20;
    cout<<"derived Constructor\n";
    }
    derived(derived &a)
    {
    cout<<"derived Copy Constructor\n";
    a.j=j;
    cout<<j<<endl;
    }

    ~derived()
    {
    cout<<"derived Destructor\n";
    }

    };

    main()
    {
    base obj;
    base obj1=obj;

    derived ob;
    derived ob1=ob;

    }

i am a beginner in cpp i was trying to understand single inheritance how it behaves how its const,dest behaves but got a problem in the derived class derived member giving garbage value.. can somebody explain me.

도움이 되었습니까?

해결책

Your copy constructors are wrong. You are copying to the source rather than destination. Try replacing:

base(base &a)
{
  cout<<"base Copy Constructor\n";
  a.i=i;
}

With:

base(base &a)
{
  cout<<"base Copy Constructor\n";
  i = a.i;
}

AND

derived(derived &a)
{
  cout<<"derived Copy Constructor\n";
  a.j=j;
  cout<<j<<endl;
}

with

derived(derived &a)
{
  cout<<"derived Copy Constructor\n";
  j=a.j;
  cout<<j<<endl;
}

다른 팁

Your copy constructors are implemented incorrectly.

You are modifying the object being passed in, not the object you are constructing. Try this with:

i=a.i;

and

j=a.j;

in your copy constructors, instead of the other way around.

This should (probably) do what it looks like you're trying to do, and you should be able to see why the way you are currently doing it is resulting in uninitialised member variables.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top