C++ Session1 15 June 2025
C++ Session1 15 June 2025
around objects rather than functions and logic. Key OOP concepts in C++ include:
#include <iostream>
#include <string>
};
int main() {
myObj.myNum = 15;
// Print values
return 0;
}
3. Encapsulation and Data Abstraction: Combining data and functions into a single unit.
#include <iostream>
#include <string>
// Base class
class Vehicle {
public:
void honk() {
};
// Derived class
public:
};
int main() {
Car myCar;
myCar.honk();
return 0;
5. Polymorphism: Ability to present the same interface for different data types.
• Reserved words (like C++ keywords, such as int) cannot be used as names
#include <iostream>
using namespace std;
int main() {
int x = 5, y = 6, z = 50;
cout << x + y + z;
return 0;
}
How to do Scanf in C++;
#include <iostream>
int main () {
x;
cout << "Type a number: "; // Type a number and press enter
return 0;
C++ Comments
Comments can be used to explain C++ code, and to make it more readable. It can also be used
to prevent execution when testing alternative code. Comments can be singled-lined or multi-
lined.
Single-line Comments
Any text between // and the end of the line is ignored by the compiler (will not be executed).
In C++, there are different types of variables (defined with different keywords), for example:
• int - stores integers (whole numbers), without decimals, such as 123 or -123
• double - stores floating point numbers, with decimals, such as 19.99 or -19.99
• char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
• string - stores text, such as "Hello World". String values are surrounded by double quotes
To declare more than one variable of the same type, use a comma-separated list:
#include <iostream>
int main() {
int x, y, z;
x = y = z = 50;
cout << x + y + z;
return 0;
}
C++ Identifiers
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
Constants
When you do not want others (or yourself) to change existing variable values, use
the const keyword (this will declare the variable as "constant", which means unchangeable and
read-only):
Example
Example
The data type specifies the size and type of information the variable will store: