I'm having trouble understanding this challenge question (C++) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I'm having trouble understanding this challenge question (C++)

So here's the question: What's the output? #include <iostream> using namespace std; class A { public: virtual void f() { cout << 1; } }; class B: public A { private: void f() { cout << 2; } }; void c(A &a) { a.f(); } int main() { B b; c(b); return 0; } The output is 2. However, I noticed that if you remove the '&' from the c function, it returns 1 instead. I've been trying to search online about how passing parameters like this works, but the example always use pointers (ie: something like A* a or int* x instead). HOWEVER, when you try to use a pointer here, it tells me that the argument cannot be converted from class 'B' to 'A'. Which, to me, makes sense. I still just don't understand why using &a works here. Thank you in advance if you're able to help me understand this :D

27th Oct 2017, 1:37 AM
Christian Barraza
Christian Barraza - avatar
2 Answers
+ 2
Thank you, Gordie. You're awesome, and I just learned a lot from that lesson. I guess I should really go through that website if I really want to understand C++.
27th Oct 2017, 3:41 AM
Christian Barraza
Christian Barraza - avatar
+ 1
@Gordie Could you possibly point out my error? I simply changed '&a' to '*a' and it's still the error I get. (Also tried A* a just in case). Also, still reading through the link. https://code.sololearn.com/cHlhkxCo3q1a/?ref=app
27th Oct 2017, 3:16 AM
Christian Barraza
Christian Barraza - avatar