+ 3

Explain the output

Please explain clearly how to find the output of the code below? class A{ public: 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); }

4th Oct 2017, 8:29 AM
SAKSHI
SAKSHI - avatar
1 Answer
+ 10
class A is your base class. class B is a derived class from A. int main(){ // Instantiate an object of type B derived from type A B b; // This function call, feed object b by reference to friend function's "void C(A &a)" parameter list C(b); } // This friend function with a ctor(copy constructor) as its parameter, assign an object of type B to A void C(A &a) { // invoking type A's f function using newly constructed object a a.f(); } As a result, "cout << 1" will be executed and you will have 1 on your console window.
4th Oct 2017, 9:17 AM
Babak
Babak - avatar