// deriv_VirtualFunctions2.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
class Base {
public:
virtual void NameOf(); // Virtual function.
void InvokingClass(); // Nonvirtual function.
};
// Implement the two functions.
void Base::NameOf() {
cout << "Base::NameOf\n";
}
void Base::InvokingClass() {
cout << "Invoked by Base\n";
}
class Derived : public Base {
public:
void NameOf(); // Virtual function.
void InvokingClass(); // Nonvirtual function.
};
// Implement the two functions.
void Derived::NameOf() {
cout << "Derived::NameOf\n";
}
void Derived::InvokingClass() {
cout << "Invoked by Derived\n";
}
int main() {
// Declare an object of type Derived.
Derived aDerived;
// Declare two pointers, one of type Derived * and the other
// of type Base *, and initialize them to point to aDerived.
Derived *pDerived = &aDerived;
Base *pBase = &aDerived;
// Call the functions.
pBase->NameOf(); // Call virtual function.
pBase->InvokingClass(); // Call nonvirtual function.
pDerived->NameOf(); // Call virtual function.
pDerived->InvokingClass(); // Call nonvirtual function.
}
correct c++ output:
Derived::NameOf
Invoked by Base
Derived::NameOf
Invoked by Derived
I have tried but failed, please help me.
class Base {
// Abstract function
nameOf(): void {
console.log("Base::nameOf");
}
invokingClass(): void {
console.log("Invoked by Base");
}
}
class Derived extends Base {
nameOf(): void {
console.log("Derived::nameOf");
}
invokingClass(): void {
console.log("Invoked by Derived");
}
}
const aDerived = new Derived();
const pDerived = aDerived;
const pBase: Base = aDerived;
pBase.nameOf();
(pBase as Base).invokingClass();
pDerived.nameOf();
pDerived.invokingClass();
These typescript output wrong result:
"Derived::nameOf"
"Invoked by Derived"
"Derived::nameOf"
"Invoked by Derived"