


Khusboo Tayal
This tutorial dives into advanced C++ concepts that enable you to write more efficient, powerful, and scalable C++ code. It covers advanced techniques and language features that transform you from an intermediate to an advanced C++ developer.
Advanced C++ concepts are features and techniques that provide:
Smart pointers are part of the <memory> header and automatically manage memory, ensuring that memory is properly freed.
#include <iostream>
#include <memory>
using namespace std;
int main() {
unique_ptr<int> ptr = make_unique<int>(10);
cout << "Unique Pointer Value: " << *ptr << endl;
return 0;
}
Unique Pointer Value: 10
#include <iostream>
#include <memory>
using namespace std;
int main() {
shared_ptr<int> sp1 = make_shared<int>(20);
shared_ptr<int> sp2 = sp1; // Shared ownership
cout << "Shared Pointer Value: " << *sp1 << endl;
cout << "Reference Count: " << sp1.use_count() << endl;
return 0;
}
Shared Pointer Value: 20 Reference Count: 2
#include <iostream>
#include <fstream>
using namespace std;
class FileManager {
ofstream file;
public:
FileManager(const string &filename) {
file.open(filename);
cout << "File opened." << endl;
}
~FileManager() {
file.close();
cout << "File closed." << endl;
}
};
int main() {
{
FileManager fm("example.txt");
} // FileManager goes out of scope here
return 0;
}
File opened. File closed.
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec1 = {1, 2, 3};
vector<int> vec2 = move(vec1); // Move resources
cout << "vec1 size: " << vec1.size() << endl;
cout << "vec2 size: " << vec2.size() << endl;
return 0;
}
vec1 size: 0 vec2 size: 3
#include <iostream>
using namespace std;
template <typename T>
void print(T &&value) {
cout << "Value: " << value << endl;
}
int main() {
int x = 42;
print(x); // L-value
print(42); // R-value
return 0;
}
Value: 42 Value: 42
#include <iostream>
using namespace std;
int main() {
auto sum = [](int a, int b) -> int {
return a + b;
};
cout << "Sum: " << sum(5, 3) << endl;
return 0;
}
Sum: 8
#include <iostream>
using namespace std;
class Multiply {
public:
int operator()(int a, int b) {
return a * b;
}
};
int main() {
Multiply multiply;
cout << "Multiplication: " << multiply(4, 5) << endl;
return 0;
}
Multiplication: 20
#include <iostream>
using namespace std;
int main() {
auto x = 10;
decltype(x) y = 20;
cout << "x: " << x << ", y: " << y << endl;
return 0;
}
x: 10, y: 20
#include <iostream>
#include <type_traits>
using namespace std;
template <typename T>
typename enable_if<is_integral<T>::value, T>::type
printValue(T value) {
cout << "Integer Value: " << value << endl;
}
int main() {
printValue(42);
// printValue(3.14); // Error: Not an integer
return 0;
}
Integer Value: 42