Reputation: 1708
I have following code in C++
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
class A{
public:
int x;
int y;
int first(){
return x;
}
int second(){
return y;
}
};
class C{
public:
float a,b;
C(){
a = 0.0f;
b = 0.0f;
}
template<class T>
C(T t){
cout<<"Copy Constructor\n";
a = t.first();
b = t.second();
}
template<class T>
C & operator=(T const &c){
cout <<"Assignment operator\n";
this->a = c.first();
this->b = c.first();
}
};
class D: public C{
public:
template <typename T> D (T t) : C(t) {}
float area(){
return a*b;
}
};
int main(){
A a;
a.x = 6;
a.y = 8;
C c(a);
D d(a);
D e = a; // Here copy constructor is being called!!
cout<<e.a<<" "<<e.b<<" "<<e.area()<<endl;
}
Here is the output of the above program
Copy Constructor
Copy Constructor
Copy Constructor
6 8 48
Why is assignment operator not being called in derived class?
Edit1 : I have changed the question to make the question more clear.
Upvotes: 0
Views: 202
Reputation: 6357
You can grab back said operator= explicitly using :
using C::operator=
in D class.
operator= are inherited but masked by default by th eone generated by th ecompiler.
Upvotes: 0
Reputation: 7002
Constructors are not inherited as regular public functions. Default constructor are defined by the compiler if missing, but you should define a constructor taking an A
parameter (or templated as you did for C
) for D
. You will need an assignment operator to be defined as well.
class D: public C{
public:
D(A aparam)
: a(aparam.first(), b(aparam.second()){
}
D& operator=(const D& rhs){
a = rhs.first();
b = rhs.second();
}
float area(){
return a*b;
}
};
Upvotes: 2