Classes and Objects
In C++, classes are used to define objects. A class is a blueprint that defines the properties and behaviors that an object of that class will have.
To define a class in C++, you can use the class
keyword followed by the name of the class.
1// Class definition
2
3class Car {
4 // Class members
5};
The class can have attributes (properties) and methods (functions).
1// Class definition
2
3class Car {
4 // Attributes
5 string brand;
6 int year;
7
8 // Methods
9 void start() {
10 cout << "Starting the car" << endl;
11 }
12};
To create an object of a class, you can use the class name followed by the object name and optional parentheses.
1// Create an object of the Car class
2class Car myCar;
Once you have created an object, you can access its attributes and call its methods using the dot operator.
1// Access the attributes and methods of the object
2myCar.brand = "Toyota";
3myCar.year = 2020;
4
5myCar.start();
xxxxxxxxxx
using namespace std;
// Define the `Car` class
// Class definition
// constructors
// methods
int main() {
// Create an object of the `Car` class
// Access the methods and properties of the object
return 0;
}
Are you sure you're getting this? Is this statement true or false?
Classes and objects are used to define attributes and behaviors in C++.
Press true if you believe the statement is correct, or false otherwise.
Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows you to create a new class (called the derived class) from an existing class (called the base class). The derived class inherits the properties and behaviors of the base class, and can also add its own unique properties and behaviors.
In C++, inheritance is defined using the :
symbol followed by the access specifier (public
, protected
, or private
) and the name of the base class.
1// Base class
2
3class Shape {
4public:
5 // Base class members
6};
7
8// Derived class
9
10class Rectangle : public Shape {
11public:
12 // Derived class members
13};
In the example above, Rectangle
is the derived class and Shape
is the base class.
By using the public
access specifier, the derived class inherits the public members of the base class. In other words, the derived class can access and use the public members of the base class.
When an object of the derived class is created, it contains all the data members and member functions of the base class as well.
You can also override the base class member functions in the derived class to provide a different implementation. This is known as function overriding.
In the example below, the display()
member function is overridden in the Rectangle
class to provide a different implementation.
1// Base class
2
3class Shape {
4public:
5 void display() {
6 cout << "This is a shape" << endl;
7 }
8};
9
10// Derived class
11
12class Rectangle : public Shape {
13public:
14 void display() {
15 cout << "This is a rectangle" << endl;
16 }
17};
To create objects of the derived class, you can use the same syntax as creating objects of the base class.
1Shape* shape = new Shape();
2shape->display();
3
4Rectangle* rectangle = new Rectangle();
5rectangle->display();
When the display()
function is called on the shape
object, it will output "This is a shape". When the display()
function is called on the rectangle
object, it will output "This is a rectangle".
Inheritance allows for code reusability and helps in organizing and structuring the code in a logical manner. It is particularly useful in scenarios where you have common properties and behaviors shared among multiple classes, as it avoids code duplication and promotes a modular approach.
xxxxxxxxxx
}
using namespace std;
// Base class
class Shape {
public:
void display() {
cout << "This is a shape" << endl;
}
};
// Derived class
class Rectangle : public Shape {
public:
void display() {
cout << "This is a rectangle" << endl;
}
};
int main() {
Shape* shape = new Shape();
shape->display();
Rectangle* rectangle = new Rectangle();
rectangle->display();
return 0;
Are you sure you're getting this? Fill in the missing part by typing it in.
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows you to create a new class (called the ____) from an existing class (called the ____). The derived class inherits the properties and behaviors of the base class, and can also add its own unique properties and behaviors.
Write the missing line below.
Polymorphism
Polymorphism, a key concept in object-oriented programming (OOP), refers to the ability of objects of different classes to be treated as objects of a common base class. This allows for code reuse and enables behavior to be determined at runtime.
In C++, polymorphism is achieved through the use of virtual functions. A virtual function is a member function of a class that can be overridden in a derived class.
To demonstrate polymorphism, let's consider an example involving animals. We have a base class Animal
and two derived classes Dog
and Cat
. Each derived class has its own implementation of the makeSound()
function.
1// Base class
2
3class Animal {
4public:
5 virtual void makeSound() {
6 cout << "The animal makes a sound" << endl;
7 }
8};
9
10// Derived class
11
12class Dog : public Animal {
13public:
14 void makeSound() {
15 cout << "The dog barks" << endl;
16 }
17};
18
19// Derived class
20
21class Cat : public Animal {
22public:
23 void makeSound() {
24 cout << "The cat meows" << endl;
25 }
26};
In the main()
function, we can create objects of type Dog
and Cat
and use a pointer of the base class type Animal
to invoke the makeSound()
function. This is where polymorphism comes into play.
1int main() {
2 Animal* animal;
3 Dog dog;
4 Cat cat;
5
6 // Animal pointer pointing to a Dog object
7 animal = &dog;
8 animal->makeSound(); // Output: The dog barks
9
10 // Animal pointer pointing to a Cat object
11 animal = &cat;
12 animal->makeSound(); // Output: The cat meows
13
14 return 0;
15}
As you can see, when we call the makeSound()
function on the animal
pointer, the appropriate implementation is invoked based on the actual object type. This behavior is determined at runtime, allowing for flexibility in the code.
Polymorphism is a powerful OOP concept that promotes code flexibility, extensibility, and modularity. It allows for the creation of generic code that can operate on objects of different classes as long as they inherit from a common base class.
xxxxxxxxxx
}
using namespace std;
// Base class
class Animal {
public:
virtual void makeSound() {
cout << "The animal makes a sound" << endl;
}
};
// Derived class
class Dog : public Animal {
public:
void makeSound() {
cout << "The dog barks" << endl;
}
};
// Derived class
class Cat : public Animal {
public:
void makeSound() {
cout << "The cat meows" << endl;
}
};
Build your intuition. Click the correct answer from the options.
What is the main benefit of polymorphism in object-oriented programming?
Click the option that best answers the question.
- Code reusability
- Memory efficiency
- Improved performance
- Simpler syntax
Abstraction
Abstraction is a fundamental concept in object-oriented programming (OOP) that allows us to model real-world objects and systems at a higher level of complexity. It involves hiding unnecessary details and focusing on the essential characteristics of an object or system.
In C++, abstraction is achieved through the use of abstract classes. An abstract class is a class that cannot be instantiated and serves as a blueprint for other classes. It contains pure virtual functions, which are functions with no implementation in the abstract class.
1// Abstract class
2
3class Shape {
4public:
5 // Pure virtual function
6 virtual void draw() = 0;
7};
The Shape
class is an example of an abstract class in C++. It contains a pure virtual function draw()
, which is a function that must be overridden in derived classes. This allows for the creation of different shapes, such as circles and rectangles, that each have their own way of being drawn.
1// Derived class
2
3class Circle : public Shape {
4public:
5 void draw() {
6 cout << "Drawing a circle" << endl;
7 }
8};
9
10// Derived class
11
12class Rectangle : public Shape {
13public:
14 void draw() {
15 cout << "Drawing a rectangle" << endl;
16 }
17};
The Circle
and Rectangle
classes are derived classes that inherit from the Shape
class. They provide the implementation for the draw()
function specific to their shape. This allows for the flexibility to create different shapes that can be treated as Shape
objects.
1int main() {
2 Shape* shape1;
3 Shape* shape2;
4
5 Circle circle;
6 Rectangle rectangle;
7
8 shape1 = &circle;
9 shape2 = &rectangle;
10
11 shape1->draw(); // Output: Drawing a circle
12 shape2->draw(); // Output: Drawing a rectangle
13
14 return 0;
15}
In the main()
function, we create objects of the derived classes Circle
and Rectangle
and assign them to pointers of the base class type Shape
. We can then call the draw()
function on these pointers, and the appropriate implementation specific to each shape will be invoked.
Abstraction allows us to manage complexity, minimize duplication of code, and promote code flexibility. By focusing on the essential characteristics and hiding unnecessary details, abstraction enhances code readability and maintainability.
xxxxxxxxxx
}
using namespace std;
// Abstract class
class Shape {
public:
// Pure virtual function
virtual void draw() = 0;
};
// Derived class
class Circle : public Shape {
public:
void draw() {
cout << "Drawing a circle" << endl;
}
};
// Derived class
class Rectangle : public Shape {
public:
void draw() {
cout << "Drawing a rectangle" << endl;
}
};
Are you sure you're getting this? Click the correct answer from the options.
Which of the following statements about abstraction in object-oriented programming (OOP) is true?
Click the option that best answers the question.
- Abstraction allows us to focus on the essential characteristics of an object or system
- Abstraction is achieved through the use of concrete classes
- Abstraction is not important in OOP
- Abstraction can only be achieved using interfaces
Encapsulation
Encapsulation is one of the key principles of object-oriented programming (OOP) that focuses on hiding internal implementation details of a class and providing controlled access to the class's members. By encapsulating data and methods together, encapsulation helps create objects that are self-contained and modular.
In C++, encapsulation is achieved by using access specifiers to control the visibility of class members. The three access specifiers in C++ are:
public
: Class members declared as public are accessible from any part of the program.private
: Class members declared as private are only accessible within the class itself.protected
: Class members declared as protected are accessible within the class and its derived classes.
By default, class members are private if no access specifier is specified.
Let's take a look at an example that demonstrates encapsulation in C++:
1#include <iostream>
2using namespace std;
3
4// Encapsulated class
5
6class Player {
7private:
8 string name;
9 int age;
10
11public:
12 void setName(string playerName) {
13 name = playerName;
14 }
15
16 void setAge(int playerAge) {
17 age = playerAge;
18 }
19
20 string getName() {
21 return name;
22 }
23
24 int getAge() {
25 return age;
26 }
27};
28
29int main() {
30 Player player;
31 player.setName("John Doe");
32 player.setAge(25);
33
34 cout << "Player Name: " << player.getName() << endl;
35 cout << "Player Age: " << player.getAge() << endl;
36
37 return 0;
38}
In this example, we have a class called Player
that encapsulates the name
and age
data members and provides public member functions to set and get their values. The setName
and setAge
functions are used to set the values of the private members, and the getName
and getAge
functions are used to retrieve their values.
By encapsulating the data members and providing controlled access through member functions, we ensure that the internal details of the Player
class are hidden from outside code. The main
function demonstrates how the encapsulated class can be used to create a Player
object and access its data through the public member functions.
Encapsulation enhances the security, reliability, and maintainability of code by preventing direct access to internal data and providing a consistent interface for interacting with objects. It also allows for data validation and error checking within the encapsulated class, ensuring that the data remains in a valid state.
xxxxxxxxxx
}
using namespace std;
// Encapsulated class
class Player {
private:
string name;
int age;
public:
void setName(string playerName) {
name = playerName;
}
void setAge(int playerAge) {
age = playerAge;
}
string getName() {
return name;
}
int getAge() {
return age;
}
};
int main() {
Let's test your knowledge. Click the correct answer from the options.
What is the purpose of encapsulation in object-oriented programming (OOP)?
Click the option that best answers the question.
- To hide internal implementation details of a class
- To provide controlled access to class members
- To enhance security, reliability, and maintainability of code
- All of the above
Generating complete for this lesson!