-
March 22nd, 2025, 04:30 AM
#1
derived class
This is just didactic example:
Code:
#include <iostream>
using namespace std;
struct A {
void f() { cout << "Class A" << endl; }
};
struct B: A {
void f() { cout << "Class B" << endl; }
};
void g(A& arg) {
arg.f();
}
int main() {
B x;
g(x);
}
When g() is invoked, A::f() is called even if the argument is referencing to B object.
At compile time, compiler knows only that the argument of function g() will be a reference to object which is derived from A.
Why compiler doesn't see that the argument x passed to a g() is type B ?
-
March 22nd, 2025, 05:04 AM
#2
Re: derived class
f() needs to be declared as virtual so that polymorphism works correctly for inherited classes.
Code:
#include <iostream>
using namespace std;
struct A {
virtual void f() {
cout << "Class A" << endl;
}
};
struct B : A {
void f() override {
cout << "Class B" << endl;
}
};
void g(A& arg) {
arg.f();
}
int main() {
B x;
g(x);
}
This shows
Class B
as expected.
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!
C++23 Compiler: Microsoft VS2022 (17.6.5)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|