If operator=() is private in base.....

Q

qazmlp

If base declares operator=() as private, is it possible for the
derived class to declare operator=() as public and allow assignment
access for it?
If no, why is it restricted so?
 
P

Peter Koch Larsen

qazmlp said:
If base declares operator=() as private, is it possible for the
derived class to declare operator=() as public and allow assignment
access for it? Yes
If no, why is it restricted so?
It is not, but you might have problems declaring a sensible operator=
considering the base class does not define this operation.

/Peter
 
R

Rolf Magnus

qazmlp said:
If base declares operator=() as private, is it possible for the
derived class to declare operator=() as public and allow assignment
access for it?

Yes. You can do that with any member function or operator.
 
S

Sharad Kala

qazmlp said:
If base declares operator=() as private, is it possible for the
derived class to declare operator=() as public and allow assignment
access for it?
If no, why is it restricted so?

Think it this way. Each derived object has a base part.
You want to keep assignment operator in base to be private.
That means you can't invoke bases' assignment operator from the derived class.
Which in turn means that when you assign objects you will keep
base part of the old object and derived part of the object you are assigning
from.

Consider this example code -

#include <iostream>
class A{
public:
int i;
A(int i): i(i){}
private:
A& operator=(const A& a)
{
this->i = a.i;
return *this;
}
};

class B: public A{
public:
int j;
B(int i, int j): A(i), j(j) {}
B& operator=(const B&b)
{
// Can't invoke base assignment operator.
// A::eek:perator=(b);
this->j= b.j;
return *this;
}
};

int main(){
B b1(5, 2), b2(6, 4);
b1=b2;
std::cout << b1.i << " " << b1.j;
}

Output - 5 4
See the difference?

-Sharad
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,427
Latest member
HildredDic

Latest Threads

Top