Conditionals
Conditionals in C++ are used to perform different actions based on different conditions. The if
, else if
, and else
statements are commonly used.
class ConditionalExample {
public:
void checkNumber(int number) {
if (number > 0) {
std::cout << "Number is positive\n";
} else if (number < 0) {
std::cout << "Number is negative\n";
} else {
std::cout << "Number is zero\n";
}
}
};
Switch
The switch statement in C++ allows a variable to be tested for equality against a list of values.
class SwitchExample {
public:
void dayOfWeek(int day) {
switch (day) {
case 1: std::cout << "Monday\n"; break;
case 2: std::cout << "Tuesday\n"; break;
//... other cases
default: std::cout << "Invalid day\n";
}
}
};
Bucle (Loops)
Loops in C++ are used to repeatedly execute a block of code. Here’s an example using a for
loop.
class LoopExample {
public:
void printNumbers(int n) {
for (int i = 1; i <= n; i++) {
std::cout << i << " ";
}
std::cout << "\n";
}
};
Vectors
Vectors in C++ are sequence containers representing arrays that can change in size.
#include <vector>
class VectorExample {
public:
std::vector<int> createVector(int size) {
std::vector<int> vec(size, 0); // Vector of given size with all values initialized to 0
return vec;
}
};
Matrix
Matrix implementation can be done using a vector of vectors.
#include <vector>
class MatrixExample {
public:
std::vector<std::vector<int>> createMatrix(int rows, int cols) {
std::vector<std::vector<int>> mat(rows, std::vector<int>(cols, 0));
return mat;
}
};
Class and Objects
Class
A class in programming is a blueprint or a template for creating objects. It defines the characteristics and behaviors that objects of that class will have. A class encapsulates data (attributes) and functions (methods) that operate on that data within a single unit.
Attributes represent the state of an object and can be of various data types, such as integers, strings, or custom-defined types. Methods define the actions or operations that can be performed on the object.
A class can have visibility specifiers, such as public
, private
, and protected
, which control the accessibility of its members. public
members are accessible from outside the class, private
members are only accessible within the class itself, and protected
members are accessible within the class and its derived classes.
Classes are the fundamental building blocks of object-oriented programming (OOP). They promote code reusability, maintainability, and help organize code into logical units.
Elements
- Attributes: These are data members that hold the state of the object. They can be of any data type.
- Methods: Functions defined inside a class that operate on or with the object’s attributes.
- Visibility: The access specifiers (
private
,public
, andprotected
) control the visibility of the members of a class.private
members are accessible only within the class,public
members are accessible from outside the class, andprotected
members are accessible within the class and its derived classes. - Direct and Indirect Access: Direct access refers to accessing members of a class directly using the dot operator. Indirect access involves using methods to manipulate or access the members, typically used for
private
members.
Object
An object is an instance of a class. When a class is defined, it acts as a blueprint, specifying the attributes and behaviors that objects of that class should possess. When an object is created, memory is allocated to store its attributes and methods.
An object represents a unique entity with its own state and behavior. The state of an object is determined by its attribute values, while the behavior is defined by the methods associated with the class.
Objects can interact with each other by invoking methods or accessing attributes of other objects. They can also be used to represent real-world entities, such as a person, car, or bank account, as well as abstract concepts or data structures.
Object-oriented programming allows for the creation of multiple objects from a single class, each with its own identity, state, and behavior. This concept of object instantiation enables modular and reusable code, as objects can be created, manipulated, and controlled independently.
Elements
- State: Refers to the current values of an object’s attributes.
- Identity: While the state of two objects can be identical, their identities are not. Each object occupies a unique memory location.
- Abstraction and Encapsulation: Abstraction means exposing only the necessary details to the user, hiding the internal implementation. Encapsulation involves bundling the data (attributes) and the methods that operate on the data into a single unit (class), and keeping the details hidden.
Examples in C++
Full example with class and objects
A full combination of all the examples with classes and objects.
class Car {
private: // Encapsulation
std::string color; // Attribute
int speed; // Attribute
public:
Car(std::string c, int s) : color(c), speed(s) {} // Constructor
void accelerate() { // Method
speed += 10;
}
void display() const { // Method showing state
std::cout << "Car color: " << color << ", Speed: " << speed << " km/h\n";
}
// Getter and Setter for encapsulation and direct/indirect access
void setColor(std::string c) {
color = c;
}
std::string getColor() const {
return color;
}
};
Usage Example
int main() {
ConditionalExample ce;
ce.checkNumber(5);
SwitchExample se;
se.dayOfWeek(3);
LoopExample le;
le.printNumbers(5);
VectorExample ve;
auto vec = ve.createVector(10);
MatrixExample me;
auto mat = me.createMatrix(3, 3);
Car car("Red", 50);
car.accelerate();
car.display();
return 0;
}
This code provides a basic structure for each concept. Each class is designed to demonstrate a specific concept and should be extended or modified as needed to fit more complex scenarios or requirements.
Student class example
#include <iostream>
#include <string>
class Student {
private:
std::string name; // Attribute (Encapsulation)
int age; // Attribute (Encapsulation)
public:
// Constructor (Method for initialization)
Student(std::string n, int a) : name(n), age(a) {}
// Method to display student info (Abstraction)
void display() const {
std::cout << "Name: " << name << ", Age: " << age << std::endl;
}
// Getter (Indirect access to private attribute)
int getAge() const {
return age;
}
// Setter (Indirect access to private attribute)
void setAge(int a) {
if (a > 0) {
age = a;
}
}
// Additional methods can be added here...
};
int main() {
Student student("Alice", 20); // Creating an object
student.display(); // Direct access to public method
std::cout << "Student's initial age: " << student.getAge() << std::endl; // Indirect access to private attribute
student.setAge(21); // Indirect access to modify private attribute
student.display(); // State of the object is now changed
return 0;
}
In this example:
Student
Class: Defines the blueprint for student objects with attributes (name
,age
) and methods (display
,getAge
,setAge
).- Visibility: The
name
andage
attributes areprivate
, meaning they cannot be accessed directly outside the class. - Object:
student
is an instance of theStudent
class. - State: Defined by the values of
name
andage
. For instance, the state changes whenage
is updated. - Identity: Each object of
Student
(e.g.,student
) has a unique memory location. - Abstraction: The
display
method provides a simple interface for showing student details, hiding the implementation. - Encapsulation:
name
andage
are encapsulated within theStudent
class, and their access is controlled through public methods (getAge
andsetAge
).
This example illustrates the fundamental concepts of classes and objects in C++, demonstrating how they can be used to create structured and maintainable code.