0% found this document useful (0 votes)
168 views26 pages

BPLCK205D Module-1

Uploaded by

Manik Kalhotra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
168 views26 pages

BPLCK205D Module-1

Uploaded by

Manik Kalhotra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Module-1 Introduction to Object Oriented Programming BPLCK205D

Module-1 Intoduction to Object Oriented Programming

Q.1. What is C++ ? List the applications of C++


C++ is a general-purpose, free-form programming language created by Bjarne Stroustrup in 1979
at Bell Labs in Murray Hill, New Jersey, as an enhancement to the C language
Applications :
● Operating Systems
C++ is a fast and strongly-typed programming language which makes it an ideal choice for
developing operating systems. Mac OS X has large amounts written in C++. Most of the
software from Microsoft like Windows, Microsoft Office, IDE Visual Studio, and Internet
Explorer are also written in C++.
● Games
Since C++ is closer to hardware, game development companies use it as their primary choice to
develop gaming systems. It can easily manipulate resources and can override the complexities of
3D games and multiplayer networking.
● GUI Based Applications
C++ is also used to develop GUI-based and desktop applications. Most of the applications from
Adobe such as Photoshop, Illustrator, etc. are developed using C++.
● Web Browsers
Web browsers need to be fast in execution as people do not like to wait for their web pages to be
loaded. This is why most browsers are developed in C++ for rendering purposes. Mozilla Firefox
is completely developed from C++. Google applications like Chrome and Google File System
are partly written in C++.
● Embedded Systems
Various embedded systems that require the program to be closer to hardware such as
smartwatches, medical equipment systems, etc., are developed in C++. It can provide a lot of
low-level function calls, unlike other high-level programming languages.
● Banking Applications
Since banking applications require concurrency, multi-threading, concurrency, and high
performance, C++ is the default choice of programming language. Infosys Finacle is a popular
banking application developed using C++.

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++.

Q.2. What are the features of C++


● C++ is one of the world's most popular programming languages.
● C++ can be found in today's operating systems, Graphical User Interfaces, and embedded
systems.
● C++ is an object-oriented programming language which gives a clear structure to
programs and allows code to be reused, lowering development costs.
● C++ is portable and can be used to develop applications that can be adapted to multiple
platforms.
● C++ is fun and easy to learn!

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

Q.3. Describe the structure of C++ program with examples ?

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: Every C++ statement ends with a semicolon ;.

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 6: return 0 ends the main function.

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 ?

OOP stands for Object-Oriented Programming.

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.

Object-oriented programming has several advantages over procedural programming:

● OOP is faster and easier to execute


● OOP provides a clear structure for the programs
● OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
● OOP makes it possible to create full reusable applications with less code and shorter
development time

Classes and Objects

Dept.of. AIML 4
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D

C++ is an object-oriented programming language.

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

Create a class called "student":

class student { // The class


public: // Access specifier
int usn; // Attribute (int variable)
string name; // Attribute (string variable)

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:

class student { // The class


public: // Access specifier
int usn; // Attribute (int variable)
string name; // Attribute (string variable)
};

int main() {
student stu; // Create an object of student

// Access attributes and set values


stu.usn = 15;
stu.name = "vaibhav";

// Print attribute values


cout << stu.usn << "\n";
cout << stu.name;
return 0;
}

Creating Multiple objects :

Dept.of. AIML 6
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D

// Create a Car class with some attributes


class Car {
public:
string brand;
string model;
int year;
};

int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;

// Create another object of Car


Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;

// Print attribute values


cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}

Q.5. Illustrate the Class methods with an example program ?


Class Methods
Methods are functions that belongs to the class.

There are two ways to define functions that belongs to a class:

Inside class definition


Outside class definition
In the following example, we define a function inside the class, and we name it "myMethod".

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
};

// Method/function definition outside the class


void MyClass::myMethod() {
cout << "Hello World!";
}

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 Car::speed(int maxSpeed) {


return maxSpeed;
}

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

// Pure virtual functions


virtual void start() const = 0;
virtual void stop() const = 0;
virtual void accelerate() const = 0;
};

// Concrete derived class


class Car : public Vehicle {
public:
void start() const override {
std::cout << "Car starting." << std::endl;
}

void stop() const override {


std::cout << "Car stopping." << std::endl;
}

void accelerate() const override {


std::cout << "Car accelerating." << std::endl;
}
};

// Concrete derived class


class Motorcycle : public Vehicle {
public:
void start() const override {
std::cout << "Motorcycle starting." << std::endl;
}

void stop() const override {

Dept.of. AIML 13
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D

std::cout << "Motorcycle stopping." << std::endl;


}

void accelerate() const override {


std::cout << "Motorcycle accelerating." << std::endl;
}
};

int main() {
// Create objects of derived classes
Car car;
Motorcycle motorcycle;

// Interact with vehicles using the abstract base class pointer


Vehicle* vehicle1 = &car;
Vehicle* vehicle2 = &motorcycle;

// Call the functions without worrying about the internal details


vehicle1->start();
vehicle1->accelerate();
vehicle1->stop();

vehicle2->start();
vehicle2->accelerate();
vehicle2->stop();

return 0;
}

Encapsulation:

Dept.of. AIML 14
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D

● Encapsulation is a fundamental principle of object-oriented programming that involves


bundling data and related methods into a single unit called a class.
● It provides data hiding and protects the internal state of an object from direct access or
modification by external code.
● Access to the object's data is typically controlled through public, private, and protected
access specifiers.
Example:
Consider a "BankAccount" class that encapsulates the account details and operations. The
account balance and transaction history can be private members of the class, accessible only
through member functions like deposit(), withdraw(), and getBalance(). By encapsulating the
data, we ensure that it is accessed and modified in a controlled manner, maintaining the integrity
and security of the account.

#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) {}

void deposit(double amount) {


balance += amount;
transactionHistory.push_back("Deposit: +" + std::to_string(amount));
}

Dept.of. AIML 15
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D

void withdraw(double amount) {


if (balance >= amount) {
balance -= amount;
transactionHistory.push_back("Withdrawal: -" + std::to_string(amount));
} else {
std::cout << "Insufficient balance." << std::endl;
}
}

double getBalance() const {


return balance;
}

void printTransactionHistory() const {


std::cout << "Transaction History:" << std::endl;
for (const std::string& transaction : transactionHistory) {
std::cout << transaction << std::endl;
}
}
};
int main() {
BankAccount account("1234567890", 1000.0);
account.deposit(500.0);
account.withdraw(200.0);
account.withdraw(2000.0); // Insufficient balance
double balance = account.getBalance();
std::cout << "Current balance: " << balance << std::endl;
account.printTransactionHistory();
return 0;
}

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;
};

class Rectangle : public Shape {


private:
double length;
double width;

public:
Rectangle(double length, double width) : length(length), width(width) {}

double getArea() const override {


return length * width;
}

double getPerimeter() const override {


return 2 * (length + width);
}
};

class Circle : public Shape {


private:
double radius;

public:
Circle(double radius) : radius(radius) {}

Dept.of. AIML 18
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D

double getArea() const override {


return M_PI * radius * radius;
}

double getPerimeter() const override {


return 2 * M_PI * radius;
}
};

class Triangle : public Shape {


private:
double side1;
double side2;
double side3;

public:
Triangle(double side1, double side2, double side3)
: side1(side1), side2(side2), side3(side3) {}

double getArea() const override {


// Using Heron's formula to calculate the area
double s = (side1 + side2 + side3) / 2;
return sqrt(s * (s - side1) * (s - side2) * (s - side3));
}

double getPerimeter() const override {


return side1 + side2 + 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);

// Use polymorphism to call shape-specific methods


Shape* shape1 = &rectangle;
std::cout << "Rectangle area: " << shape1->getArea() << std::endl;
std::cout << "Rectangle perimeter: " << shape1->getPerimeter() << std::endl;

Shape* shape2 = &circle;


std::cout << "Circle area: " << shape2->getArea() << std::endl;
std::cout << "Circle perimeter: " << shape2->getPerimeter() << std::endl;

Shape* shape3 = &triangle;


std::cout << "Triangle area: " << shape3->getArea() << std::endl;
std::cout << "Triangle perimeter: " << shape3->getPerimeter() << std::endl;

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() {}
};

class Rectangle : public Shape {


private:
double length;
double width;

public:
Rectangle(double length, double width) : length(length), width(width) {}

double getArea() const override {


return length * width;
}
};

class Circle : public Shape {


private:

Dept.of. AIML 21
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D

double radius;

public:
Circle(double radius) : radius(radius) {}

double getArea() const override {


return M_PI * radius * radius;
}
};

class Triangle : public Shape {


private:
double side1;
double side2;
double side3;

public:
Triangle(double side1, double side2, double side3)
: side1(side1), side2(side2), side3(side3) {}

double getArea() const override {


// Using Heron's formula to calculate the area
double s = (side1 + side2 + side3) / 2;
return sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
};

double calculateArea(const Shape* shape) {


return shape->getArea();
}

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);

// Create a collection of Shape pointers


std::vector<Shape*> shapes;
shapes.push_back(&rectangle);
shapes.push_back(&circle);
shapes.push_back(&triangle);

// Calculate the area for each shape


for (const Shape* shape : shapes) {
std::cout << "Area: " << calculateArea(shape) << std::endl;
}

// Clean up the memory


for (Shape* shape : shapes) {
delete shape;
}

return 0;
}

Dept.of. AIML 23
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D

Q.8. Explain message passing in with a suitable example.


● Message passing is a method of communication between objects in object-oriented
programming, where objects send and receive messages to interact with each other.
● It allows objects to invoke methods or exchange data with other objects, enabling them to
collaborate and perform tasks collectively.
Here's an example to illustrate message passing:
Let's consider a scenario of a messaging application where users can send messages to each
other. We can represent this using two classes: User and Message.

#include <iostream>
#include <string>
class User {
std::string username;

public:
User(const std::string& name) : username(name) {}

void receiveMessage(const std::string& sender, const std::string& message) {


std::cout << username << " received a message from " << sender << ": " << message <<
std::endl;
}

void sendMessage(User& receiver, const std::string& message) {


std::cout << username << " sent a message to " << receiver.getUsername() << ": " <<
message << std::endl;
receiver.receiveMessage(username, message);
}

std::string getUsername() const {


return username;

Dept.of. AIML 24
GMIT, Davangere
Module-1 Introduction to Object Oriented Programming BPLCK205D

}
};

int main() {
User user1("Kavitha");
User user2("Meghana");

user1.sendMessage(user2, "Hello, Meghana! How are you?");

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

You might also like