I recently watched a YouTube video from "Low Level Learning" where, at 03:38
, it was mentioned that "functions with the same signature in the derived class are virtual in the parent by default." I'm unsure if I misunderstood, but it seems to imply that when a derived class has a method with the same signature as one in the parent class, the method in the parent class becomes virtual, even if the virtual
keyword is not explicitly used.
I have a few questions that formed in my mind regarding this statement:
Is the statement true? Does having functions with the same signature in the derived class make them automatically virtual in the parent class?
Additionally, is it valid to use
sizeof()
on a base class to determine if a parent-derived class uses a vtable?
To verify my understanding of this, I created the following program in C++:
#include <iostream>
struct Base {
int num;
Base(int num) : num(num) {}
void greet() {
std::cout << "Hello " << num << " from Base Class\n";
}
float operator()(int n) const { return n * num; }
};
struct Derived : public Base {
float num;
Derived(float num) : Base(1), num(num) {}
void greet() {
std::cout << "Hello " << num << " from Derived Class\n";
}
float operator()(int n) const { return n * num; }
};
int main() {
Base base(5);
Derived derived(8.8);
base.greet();
derived.greet();
std::cout << "sizeof(base) = " << sizeof(base) << "\n";
std::cout << "sizeof(derived) = " << sizeof(derived) << "\n";
std::cout << "base(3) = " << base(3) << "\n";
std::cout << "derived(3) = " << derived(3) << "\n";
return 0;
}
Based on my understanding, if a class uses a vtable, it should result in a different expected sizeof()
value compared to a class without a vtable. However, in my program, the size remains unchanged, whereas declaring some parent class methods as virtual does increase the size.
I would appreciate clarification on these questions and an explanation. Thank you!