C++ Programming - OOPS Concepts - Discussion
Discussion Forum : OOPS Concepts - General Questions (Q.No. 38)
38.
What happens if the base and derived class contains definition of a function with same prototype?
Discussion:
22 comments Page 3 of 3.
Khushbu said:
8 years ago
This is wrong only base class is executed bcoj both have same prototype if we call them reverse ie base class as derived or vice versa then what is the difference between them.
Ankit said:
8 years ago
Given answer is correct.
#include <iostream>
using namespace std;
class A
{
public:
void f() { cout << "A plain" << endl; }
};
class B : public A
{ public:
void f() { cout << "B plain" << endl; }
};
int main(){
A a;
B b;
a.f();
b.f();
}
o/p : A plain
B plain
Reason : It does so because methods of both classes are unknown to each other. They do need 'virtual' keyword if u intend to use method overriding i.e. Polymorphism which implemented using references and pointers.
#include <iostream>
using namespace std;
class A
{
public:
void f() { cout << "A plain" << endl; }
};
class B : public A
{ public:
void f() { cout << "B plain" << endl; }
};
int main(){
A a;
B b;
a.f();
b.f();
}
o/p : A plain
B plain
Reason : It does so because methods of both classes are unknown to each other. They do need 'virtual' keyword if u intend to use method overriding i.e. Polymorphism which implemented using references and pointers.
(1)
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers