Welcome to our deep dive into C++! Today, we'll explore two essential concepts: typename and class. Let's get started! š
Before we dive into typename and class, let's briefly review some fundamental concepts in C++:
int, char, float, etc.Now, let's move on to our main topics!
A class in C++ is a user-defined data type that helps group variables and functions together. It serves as a blueprint for creating objects (or instances) that can store and manipulate data.
#include <iostream>
class MyClass {
public:
int myNumber;
void setNumber(int number) {
myNumber = number;
}
int getNumber() {
return myNumber;
}
};
int main() {
MyClass myObj;
myObj.setNumber(10);
std::cout << "The number is: " << myObj.getNumber() << std::endl;
return 0;
}In this example, MyClass is a class with a variable myNumber and two functions, setNumber and getNumber. In the main function, we create an object myObj of type MyClass and set its number to 10, then print it out.
typename is a keyword in C++ that can be used in template declarations and specializations. It helps to clarify whether a name represents a type or an object.
Here's an example where we use typename inside a template function:
#include <vector>
#include <iostream>
template<typename T>
void printVector(const std::vector<T>& vec) {
for (const auto& element : vec) {
std::cout << element << ' ';
}
std::cout << std::endl;
}
int main() {
std::vector<int> intVec = {1, 2, 3, 4, 5};
std::vector<std::string> stringVec = {"one", "two", "three", "four", "five"};
printVector(intVec);
printVector(stringVec);
return 0;
}In this example, we define a template function printVector that takes a std::vector of any type T as an argument and prints its contents. We use typename inside the template function to make it clear that T is a type and not an object.
class is a user-defined data type used to create objects, whereas typename is a keyword used in template declarations and specializations to clarify whether a name represents a type or an object.class is essential for object-oriented programming, allowing you to define properties (variables) and methods (functions) within a single unit.typename is useful when dealing with templates, as it helps avoid ambiguities in template code.What is the primary purpose of a `class` in C++?
What is the purpose of the `typename` keyword in C++?