"c++novice" <be**************@yahoo.com> wrote in message
news:34**************************@posting.google.c om...
"John Harrison" <jo*************@hotmail.com> wrote in message
news:<c4*************@ID-196037.news.uni-berlin.de>... "c++novice" <be**************@yahoo.com> wrote in message
news:34**************************@posting.google.c om... 1--Can operators be virtual?
Yes.
john
perhaps an example would be more helpful.
I am confused, I tried to write some code just to understand and see
the behavior. can some body explain me.
#include <iostream>
using namespace std;
class A {
public:
A() {
this->Foo();
}
virtual void Foo() {
cout << "A::Foo()" << endl;
}
virtual A& operator=(const A &rhs){
cout << "A& operator=(const A&)" << endl;
if(this == &rhs)
return *this;
return *this;
}
// virtual A &operator++();
};
class B : public A {
public:
B() {
this->Foo();
}
virtual void Foo() {
cout << "B::Foo()" << endl;
}
virtual B& operator=(const B &rhs){
cout << "B& operator=(const B&)" << endl;
if(this == &rhs)
return *this;
return *this;
}
// virtual B &operator++();
};
int main(int, char**)
{
A objA;
B objB;
objA = objB;
B anotherobjB;
anotherobjB = objA;
return 0;
}
how can we call op= of class B?
You can't with that code. You have a A of the right hand side, but your
operator= for B takes B on the right hand side. You cannot convert an A to a
B. If you want operator= of B to be called when you have an A on the right
hand side then you have to declare like this
class B : public A
{
B& operator=(const B &rhs)
{
...
}
B& operator=(const A &rhs)
{
...
}
};
virtual has got nothing to do with it.
but op= if not declared, generated by compiler for every class then
why virtual it.
Why indeed? Why do you want a virtual operator=, what are you trying to
achieve?
You can certainly declare a virtual operator=, and it will behave exactly
like any other virtual function. But it isn't much use.
Here's some code that proves virtual operator= works.
#include <iostream>
using namespace std;
class A
{
public:
virtual A& operator=(int x) { cout << "A::operator=\n"; return *this; }
};
class B : public A
{
public:
virtual A& operator=(int x) { cout << "B::operator=\n"; return *this; }
};
int main()
{
A* a_ptr = new B();
*a_ptr = 1;
}
This code prints B::operator= but if you remove the virtuals it prints
A::operator=, which shows that virtual operator= is just like any other
virtual function.
I think your problem is that you are expecting virtual to do something that
it doesn't. Whatever it is that you are after I don't think virtual
operator= is the way to go.
If this hasn't helped then post again (perhaps in a new thread) and explain
what it is that you are trying to achieve. Someone will show you the right
way to do it.
john