#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