Reputation: 1
I create two classes: Base and Derive, and Derive is the subclass of Base. They both have a function called print and I do not use "virtual" keyword. Then, I define a template function and in the angle brackets there is an argument of type whose default value is set to Base. The argument of this function is a pointer to the type in the template. In the interior of the function I use this pointer to call the print function. It is supposed to call the Base's print function because there is no virtual keyword. However, it actually call the Derive's print function. I don't know how the template function deduce the argument type when using a default value of type. Thanks for anwering. The code is as below.
class Base {
public:
void print() { std::cout << "This is Base\n"; }
};
class Derive : public Base {
public:
void print() { std::cout << "This is Derive\n"; }
};
template <typename obj = Base>
void func(obj* ptr) {
ptr->print();
}
int main() {
Derive* d = new Derive();
func(d);
return 0;
}
The output is:
PS C:\Users\w1229\Desktop\test> cd "c:\Users\w1229\Desktop\test\" ; if ($?) { g++ test.cpp -o test } ; if ($?) { .\test }
This is Derive
PS C:\Users\w1229\Desktop\test>
Upvotes: 0
Views: 37
Reputation: 12928
The default argument is only used if the compiler can't deduce the type.
In your example you are passing in a Derived*
, so that's what the compiler deduces.
Upvotes: 1