Definition: C++ is a general-purpose programming language that supports procedural, object-oriented, and generic programming.
Explanation: Let's cover the foundational concepts:
Example:
#include <iostream>
using namespace std;
int main() {
cout << "Hello, World!";
return 0;
}
Example:
int x = 5;
if (x > 0) {
cout << "Positive number";
} else {
cout << "Non-positive number";
}
Example:
int add(int a, int b) {
return a + b;
}
int main() {
cout << add(3, 4); // Output: 7
}
Example:
int* ptr = new int; // Dynamic memory allocation
*ptr = 10; // Assign value
cout << *ptr; // Output: 10
delete ptr; // Free allocated memory
Example:
class Car {
public:
string brand;
string model;
Car(string b, string m) { // Constructor
brand = b;
model = m;
}
void display() {
cout << "Car: " << brand << " " << model;
}
};
int main() {
Car car1("Toyota", "Corolla");
car1.display(); // Output: Car: Toyota Corolla
}
Example: Template Function:
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
cout << add(5, 3); // Output: 8
cout << add(3.5, 2.5); // Output: 6.0
}