I have been studying c++ for an exam and I thought that i had understood most of the c++ commons misconcemptions with much fatigue but i've encountered an exercise from a past exam that is driving me crazy, it combines virtual methods and inheritance in a way that i dont seem to understand here is the code:
#include <iostream>
class B;
class A {
public:
virtual A* set(A* a) = 0;
};
class B : public A {
public:
virtual A* set(B* b) {
std::cout << "set1 has been called" << std::endl;
b = this;
return b;
}
virtual B* set(A* a) {
std::cout << "set2 has been called" << std::endl;
a = this;
return this;
}
};
int main(int argc, char *argv[]) {
B *b = new B();
A *a = b->set(b);
a = b->set(a);
a = a->set(b);
a = a->set(a);
return 0;
}
the output is
set1 has been called
set2 has been called
set2 has been called
set2 has been called
From what i've gathered the first call (b->set(b) ) calls the first method of class B and return b itself and then this objectref gets casted to A meaning that now the object b is now of type A?
so i have A *a = A *b;
now it makes sense to me that i should call set of A since i have this situation in my mind
objectoftypeA->set(objectoftypeA) so i m not supposed to look into virtual methods since the two object are base classes ?
Anyway as you can see I have much confusion so bear with me if i make stupid errors i would be glad if someone could explain whats going on this code,i tried to search the web but i find only small and easy example that dont cause troubles.
virtual B* set(A* a)aliasset2will act as implementation ofvirtual A* set(A* a) = 0;as aB*can implicitely be casted to anA*. Thus once you received aA*fromset1the implmentatino will be called which isset2. EDIT: Notice thatset1cant implement the pure virtual function due to its specialied parameter. Try to comment out each function. I gueess ` B *b = new B();` will cause an error ifset2is not there but not ifset1is not there.finalandoverrideto prevent accidentally writing this sort of thing.