Search⌘ K

- Examples

Explore detailed examples of C++ class templates including arrays, inheritance, and method implementations. Learn how to use templates for different data types, understand derived class access to base class methods, and apply generic operators effectively. This lesson helps you build a solid foundation in template programming to write flexible and reusable code.

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, doubleArray and accountArray, in lines 45 and 48. By calling the generic function getSize() in line 37, we can access the size of different objects.

...