BPLCK205D Module-1
BPLCK205D Module-1
Dept.of. AIML 1
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
● Compilers
The compilers of many programming languages are developed in C and C++. This is because
they are relatively lower-level when compared to other higher-level languages and are closer to
the hardware.
● Database Management Software
C++ is also used to write database management software. The world’s most popular open-source
database, MySQL, is written in C++.
As C++ is close to C, C# and Java, it makes it easy for programmers to switch to C++ or vice
versa.
Difference between C and C++
● C++ was developed as an extension of C, and both languages have almost the same
syntax.
● The main difference between C and C++ is that C++ support classes and objects, while C
does not.
Dept.of. AIML 2
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
Line 1: #include <iostream> is a header file library that lets us work with input and output
objects, such as cout (used in line 5). Header files add functionality to C++ programs.
Line 2: using namespace std means that we can use names for objects and variables from the
standard library.
Line 3: A blank line. C++ ignores white space. But we use it to make the code more readable.
Line 4: Another thing that always appear in a C++ program, is int main(). This is called a
function. Any code inside its curly brackets {} will be executed.
Line 5: cout (pronounced "see-out") is an object used together with the insertion operator (<<) to
output/print text. In our example it will output "Hello World!".
Note: The body of int main() could also been written as:
int main () { cout << "Hello World! "; return 0; }
Remember: The compiler ignores white spaces. However, multiple lines makes the code more
readable.
Line 7: Do not forget to add the closing curly bracket } to actually end the main function.
Dept.of. AIML 3
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
Omitting Namespace
You might see some C++ programs that runs without the standard namespace library. The using
namespace std line can be omitted and replaced with the std keyword, followed by the :: operator
for some objects:
Q.4. Describe OOP and Illustrate classes and objects with examples ?
Procedural programming is about writing procedures or functions that perform operations on the
data, while object-oriented programming is about creating objects that contain both data and
functions.
Dept.of. AIML 4
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
Everything in C++ is associated with classes and objects, along with its attributes and methods.
For example: in real life, a car is an object. The car has attributes, such as weight and color, and
methods, such as drive and brake.
Attributes and methods are basically variables and functions that belongs to the class. These are
often referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works as an object
constructor, or a "blueprint" for creating objects.
Creating Class
Dept.of. AIML 5
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
};
● The class keyword is used to create a class called student.
● The public keyword is an access specifier, which specifies that members (attributes and
methods) of the class are accessible from outside the class. You will learn more about
access specifiers later.
● Inside the class, there is an integer variable usn and a string variable name. When
variables are declared within a class, they are called attributes.
● At last, end the class definition with a semicolon ;.
Create an Object
In C++, an object is created from a class. We have already created the class named student, so
now we can use this to create objects.
To create an object of student , specify the class name, followed by the object name.
To access the class attributes (usn and name), use the dot syntax (.) on the object:
int main() {
student stu; // Create an object of student
Dept.of. AIML 6
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
Note: You access methods just like you access attributes; by creating an object of the class and
using the dot syntax (.):
Dept.of. AIML 7
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
Inside Example
class MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
To define a function outside the class definition, you have to declare it inside the class and then
define it outside of the class. This is done by specifying the name of the class, followed the scope
resolution :: operator, followed by the name of the function:
Outside Example
class MyClass { // The class
public: // Access specifier
void myMethod(); // Method/function declaration
};
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Adding Parameters
#include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
Dept.of. AIML 8
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
};
int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
return 0;
}
Q.6.What are abstract classes? Where are they useful? Discuss with an example
● An abstract class in C++ is a class that has at least one pure virtual function (i.e., a
function that has no definition).
● The classes inheriting the abstract class must provide a definition for the pure virtual
function; otherwise, the subclass would become an abstract class itself.
● Abstract classes are essential to providing an abstraction to the code to make it reusable
and extendable.
● For example, a Vehicle parent class with Truck and Motorbike inheriting from it is an
abstraction that easily allows more vehicles to be added. However, even though all
vehicles have wheels, not all vehicles have the same number of wheels – this is where a
pure virtual function is needed.
Here are a few reasons why abstract classes are useful in C++:
Interface definition:
● Abstract classes provide a way to define an interface that derived classes must
implement.
● By declaring pure virtual functions (functions without a definition) in the abstract class,
you enforce that any derived class must implement those functions.
● This allows you to define a common set of methods that derived classes are expected to
have.
Polymorphism:
Dept.of. AIML 9
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
● Abstract classes enable polymorphic behavior. Polymorphism allows you to treat objects
of different derived classes as objects of their common abstract base class.
● You can use a pointer or reference to the abstract class to refer to objects of any derived
class.
● This facilitates writing generic code that can work with various derived classes without
needing to know their specific implementation details.
Code organization:
● Abstract classes help in organizing your code by providing a clear separation between the
common interface and the implementation details.
● By defining an abstract class, you establish a contract that derived classes must follow,
making it easier to maintain and extend the codebase.
● It promotes the principle of encapsulation by hiding the implementation details within the
derived classes.
Runtime polymorphism:
● Since abstract classes are meant to be inherited by concrete classes, you can create
pointers or references to the abstract class and assign them to objects of derived classes.
● This allows you to achieve runtime polymorphism, where the appropriate implementation
of a method is determined dynamically at runtime based on the actual object type.
Consider an example of a Shape base class with sub-classes (Triangle and Rectangle)that inherit
the Shape class.
● Now, suppose we need a function to return the area of a shape. The function will be
declared in the Shape class; however, it cannot be defined there as the formula for the
area is different for each shape.
Dept.of. AIML 10
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
● A non-specific shape does not have an area, but rectangles and triangles do. Therefore,
the pure virtual function for calculating area will be implemented differently by each
sub-class.
The following code snippet implements the abstract Shape class along with its sub-classes:
Dept.of. AIML 11
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
Q.7. Discuss the terms abstraction, encapsulation, inheritance and polymorphism with
suitable examples.
Abstraction:
● Abstraction is the process of simplifying complex systems by focusing on essential
properties and hiding unnecessary details.
● It allows us to represent real-world entities in a simplified and generalized manner. In
programming, abstraction is achieved using abstract classes or interfaces.
● These abstract entities define a common interface that derived classes must implement.
By abstracting away the implementation details, we can work with objects at a higher
level of abstraction.
Example:
Consider a "Vehicle" abstraction. We can define a base abstract class called Vehicle with pure
virtual functions like start(), stop(), and accelerate(). Concrete derived classes like Car and
Motorcycle can implement these functions according to their specific behavior. We can then
interact with vehicles without worrying about the internal details of individual vehicle types.
#include <iostream>
// Abstract base class
class Vehicle {
public:
Dept.of. AIML 12
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
Dept.of. AIML 13
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
int main() {
// Create objects of derived classes
Car car;
Motorcycle motorcycle;
vehicle2->start();
vehicle2->accelerate();
vehicle2->stop();
return 0;
}
Encapsulation:
Dept.of. AIML 14
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
#include <iostream>
#include <vector>
class BankAccount {
private:
std::string accountNumber;
double balance;
std::vector<std::string> transactionHistory;
public:
BankAccount(const std::string& accNum, double initialBalance)
: accountNumber(accNum), balance(initialBalance) {}
Dept.of. AIML 15
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
Dept.of. AIML 16
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
❖ In this code, the BankAccount class encapsulates the account details such as the account
number (accountNumber), balance (balance), and transaction history
(transactionHistory). The data members are private, meaning they can only be accessed
through member functions of the class.
❖ The deposit() function allows depositing a given amount into the account. It updates the
account balance and records the transaction in the transaction history vector.
❖ The withdraw() function allows withdrawing a specified amount from the account if the
balance is sufficient. It subtracts the amount from the balance and records the transaction
if the balance is enough; otherwise, it displays an "Insufficient balance" message.
❖ The getBalance() function returns the current balance of the account.
❖ The printTransactionHistory() function prints the transaction history stored in the
transactionHistory vector.
❖ In the main() function, an instance of the BankAccount class is created with an initial
balance of 1000.0. Deposits and withdrawals are made, and the current balance is
retrieved and displayed. Finally, the transaction history is printed.
Inheritance:
● Inheritance is a mechanism that allows a class (derived class) to inherit the properties and
behavior of another class (base class).
● The derived class extends or specializes the functionality of the base class by adding new
members or overriding existing ones.
● It enables code reuse, promotes code organization, and supports the "is-a" relationship
between classes.
Example:
Consider a "Shape" hierarchy. We can have a base class called Shape with common properties
and methods. Derived classes like Rectangle, Circle, and Triangle can inherit from the Shape
class and provide their specific implementations. They inherit the common functionality from the
base class, such as calculating the area or perimeter, while also adding their own unique features.
#include <iostream>
#include <cmath>
Dept.of. AIML 17
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
class Shape {
public:
virtual double getArea() const = 0;
virtual double getPerimeter() const = 0;
};
public:
Rectangle(double length, double width) : length(length), width(width) {}
public:
Circle(double radius) : radius(radius) {}
Dept.of. AIML 18
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
public:
Triangle(double side1, double side2, double side3)
: side1(side1), side2(side2), side3(side3) {}
Dept.of. AIML 19
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
int main() {
// Create objects of different shapes
Rectangle rectangle(4.0, 5.0);
Circle circle(3.0);
Triangle triangle(3.0, 4.0, 5.0);
return 0;
}
Polymorphism:
● Polymorphism refers to the ability of objects of different classes to be treated as objects
of a common base class.
● It allows objects to be represented in multiple forms and enables dynamic binding of
functions at runtime.
● Polymorphism is achieved through function overriding and virtual functions.
Example:
Dept.of. AIML 20
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
Using the "Shape" hierarchy example, we can create a collection of Shape pointers that can point
to objects of different derived classes. We can call a common function like calculateArea() on
these pointers, and the appropriate implementation is determined dynamically based on the
actual object type. This allows us to write generic code that can work with different shapes
without needing to know their specific types.
#include <iostream>
#include <vector>
#include <cmath>
class Shape {
public:
virtual double getArea() const = 0;
virtual ~Shape() {}
};
public:
Rectangle(double length, double width) : length(length), width(width) {}
Dept.of. AIML 21
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
double radius;
public:
Circle(double radius) : radius(radius) {}
public:
Triangle(double side1, double side2, double side3)
: side1(side1), side2(side2), side3(side3) {}
Dept.of. AIML 22
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
int main() {
// Create objects of different shapes
Rectangle rectangle(4.0, 5.0);
Circle circle(3.0);
Triangle triangle(3.0, 4.0, 5.0);
return 0;
}
Dept.of. AIML 23
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
#include <iostream>
#include <string>
class User {
std::string username;
public:
User(const std::string& name) : username(name) {}
Dept.of. AIML 24
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
}
};
int main() {
User user1("Kavitha");
User user2("Meghana");
return 0;
}
1. We have a User class that represents a user of the messaging application. The class has a
private attribute username and three public methods:
● The constructor User(const std::string& name) initializes the username
attribute with the provided name.
● The receiveMessage(const std::string& sender, const std::string& message)
method is called when a user receives a message. It displays the sender's
username and the message content.
● The sendMessage(User& receiver, const std::string& message) method is
called when a user wants to send a message to another user. It displays the
sender's username, the receiver's username, and the message content. It also
invokes the receiveMessage() method on the receiver's object to simulate
receiving the message.
2. In the main() function, we create two User objects, user1 and user2, with usernames
"Kavitha" and "Meghana" respectively.
3. We then call the sendMessage() method on user1 and pass user2 as the receiver object
and the message "Hello, Meghana! How are you?". This simulates user1 sending a
message to user2.
Dept.of. AIML 25
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D
4. The sendMessage() method displays the sender's username, receiver's username, and the
message content. It also invokes the receiveMessage() method on user2 to simulate
user2 receiving the message.
Output :
Kavitha sent a message to Meghana: Hello, Meghana! How are you?
Meghana received a message from Kavitha: Hello, Meghana! How are you?
In this example, message passing occurs when user1 invokes the sendMessage() method on
user2. The sendMessage() method sends a message to user2 by calling the receiveMessage()
method on the receiver object. This interaction allows the two users to exchange messages in the
messaging application.
Dept.of. AIML 26
GMIT, Davangere