Search⌘ K

- Examples

Explore practical C++ template examples focusing on class templates, inheritance, and method implementations. Learn how to create template-based classes, apply inheritance with base and derived classes, and use generic operators. This lesson helps you understand how templates enhance code flexibility and reuse in real scenarios.

Example 1: Templates in Class

C++
// templateClassTemplate.cpp
#include <iostream>
class Account{
public:
explicit Account(double amount=0.0): balance(amount){}
void deposit(double amount){
balance+= amount;
}
void withdraw(double amount){
balance-= amount;
}
double getBalance() const{
return balance;
}
private:
double balance;
};
template <typename T, int N>
class Array{
public:
Array()= default;
int getSize() const;
private:
T elem[N];
};
template <typename T, int N>
int Array<T,N>::getSize() const {
return N;
}
int main(){
std::cout << std::endl;
Array<double,10> doubleArray;
std::cout << "doubleArray.getSize(): " << doubleArray.getSize() << std::endl;
Array<Account,1000> accountArray;
std::cout << "accountArray.getSize(): " << accountArray.getSize() << std::endl;
std::cout << std::endl;
}

Explanation

We have created two Array class objects, i.e., doubleArray and accountArray in lines 45 and 48. By calling generic function getSize() in line 37, we can access the size of different objects.

Example 2: Inheritance in Class Templates

...