inheritance ctors

// see main()
#include <iostream>
#include<string>


using namespace std;


class x
{
public:
x()

{
a++;

}
private:

static int a;


};
int x::a=0;



class y:public x
{

public:
y(x& tx=x(), string* tb=0):x(tx),b(tb)
{






}
y(y& rhs)
{
*this=rhs;
}
virtual y& operator=(y& rhs)
{

(x&)*this=(x&)rhs;
b=new string[6];
for(int i=0;i<6;i++)
b[i]=rhs.b[i];


return *this;

}
~y()
{
delete[]b;
}


private:
string* b;


};



class z:public y
{

public:


z(y& ty=y(),int n=0):c(n)
{
(y&)*this=ty;
}
z(z& s)
{
*this=s;
}
virtual z& operator=(z& rhs)
{
(z&)*this=(z&)rhs;
return *this;
}

private:
int c;

};

void main()
{



string *h=new string[6];
string *h1=new string[6];

for(int i=0;i<6;i++)
h[i]=h1[i]="a";

// this line is making 2 calls to base class a ctor
// cant figure.out why or how to solve the problemproblem
z s1(y(x(),h));



}
[code]"Please use code tags"[/code]
Your code shall not compile. (int main(), the references should be const)
And have several bad practices (dynamic allocation abuse, bad memory handling, casting, obfuscation)

As to why x::a is 2.
1
2
3
4
5
6
z s1(
   y(
      x(), //first increase (x::a=1)
      h
   ) //`y' calls its parent copy constructor, no increase
); //`z' calls its parent copy constructor, that calls the default for the base `x' 
You could use a step by step run (with a debugger)
How should i solve thos problem virtual keywords global varibles
Topic archived. No new replies allowed.