ODS UNIT-1 (11 MARKS)
1.Describe encapsulation, inheritance, polymorphism, and
abstraction with a C++ example.
ANS:
ENCAPSULATION
- Bundling data and methods that operate on that data within a
single unit (class or object).
- Hiding internal implementation details from the outside world.
Example:
#include <iostream>
using namespace std;
class BankAccount {
private:
double balance;
public:
void deposit(double amount) { balance += amount; }
double getBalance() { return balance; }
};
int main() {
BankAccount account;
account.deposit(1000);
cout << "Balance: " << account.getBalance() << endl;
return 0;
}
In this example, the BankAccount class encapsulates the balance data
and provides methods to deposit and retrieve the balance.
INHERITANCE
- Creating a new class based on an existing class (parent or base
class).
- The new class (child or derived class) inherits the properties and
behavior of the parent class.
Example:
#include <iostream>
using namespace std;
class Animal {
public:
void eat() { cout << "Eating..." << endl; }
};
class Dog : public Animal {
public:
void bark() { cout << "Barking..." << endl; }
};
int main() {
Dog dog;
dog.eat(); // Inherited from Animal
dog.bark();
return 0;
}
In this example, the Dog class inherits the eat() method from the
Animal class.
POLYMORPHISM
- Ability of an object to take on multiple forms.
- Can be achieved through method overloading or method
overriding.
Example:
#include <iostream>
using namespace std;
class Shape {
public:
virtual void draw() { cout << "Drawing shape..." << endl; }
};
class Circle : public Shape {
public:
void draw() override { cout << "Drawing circle..." << endl; }
};
int main() {
Circle circle;
Shape shape = circle; // Object slicing
shape.draw(); // Output: Drawing shape...
circle.draw(); // Output: Drawing circle...
return 0;
}
In this example, the Circle class overrides the draw() method of the
Shape class, demonstrating polymorphism.
ABSTRACTION
- Showing only essential features and hiding internal implementation
details.
- Helps to reduce complexity and improve modularity.
Example:
#include <iostream>
using namespace std;
class CoffeeMachine {
public:
void makeCoffee() {
boilWater();
brewCoffee();
cout << "Coffee is ready!" << endl;
}
private:
void boilWater() { cout << "Boiling water..." << endl; }
void brewCoffee() { cout << "Brewing coffee..." << endl; }
};
int main() {
CoffeeMachine machine;
machine.makeCoffee();
return 0;
}
In this example, the CoffeeMachine class abstracts the process of
making coffee, hiding the internal implementation details (boiling
water and brewing coffee) and providing a simple makeCoffee()
method.
2. Define functions. Explain about friend function with example
program.
ANS:
FUNCTION:
A function in C++ is a block of code that performs a specific task. It is
a reusable unit of code that can be called multiple times from
different parts of a program. Functions can take arguments, return
values, and can be used to:
- Perform calculations
- Manipulate data
- Control program flow
Example:
#include<iostream>
using namespace std;
void greet() {
cout << "Hello, World!" << endl;
}
int main() {
greet();
return 0;
}
FRIEND FUNCTION :
A friend function in C++ is a function that is granted access to the
private and protected members of a class. Friend functions are not
member functions of the class, but they can access the class's private
and protected members as if they were member functions.
KEY CHARACTERISTICS:
- Declared inside the class with the friend keyword
- Can access private and protected members of the class
- Not a member function of the class
- Can be used to overload operators or perform other operations that
require access to private members
EXAMPLE:
#include<iostream>
using namespace std;
class Box {
private:
int width;
public:
Box() : width(10) {} // Public constructor
friend void printWidth(Box box);
};
void printWidth(Box box) {
cout << "Width of the box: " << box.width << endl;
}
int main() {
Box box;
printWidth(box);
return 0;
}
3. Describe static variables and methods; explain differences from
non-static members with examples.
ANS:
STATIC VARIABLES
A static variable is a variable that is shared by all instances of a class.
It is initialized only once, and all instances of the class access the
same variable.
Example:
class Counter {
public:
static int count; // Declare static variable
Counter() { count++; }
};
int Counter::count = 0; // Initialize static variable
int main() {
Counter c1;
Counter c2;
Counter c3;
cout << "Count: " << Counter::count << endl; // Output: Count: 3
return 0;
}
In this example, the count variable is shared by all instances of the
Counter class.
STATIC METHODS
A static method is a method that belongs to the class itself, rather
than to any particular instance. It can access only static variables and
cannot access non-static variables.
Example:
class Maths {
public:
static int add(int a, int b) { return a + b; }
};
int main() {
int result = Maths::add(2, 3);
cout << "Result: " << result << endl; // Output: Result: 5
return 0;
}
In this example, the add method is a static method that can be called
without creating an instance of the MathUtils class.
DIFFERENCES FROM NON-STATIC MEMBERS
Here are the key differences between static and non-static members:
- Scope: static members belong to the class itself, while non-static
members belong to instances of the class.
- Initialization: static variables are initialized only once, while non-
static variables are initialized for each instance of the class.
- Access: static methods can access only static variables, while non-
static methods can access both static and non-static variables.
Example:
class Example {
public:
static int staticVar;
int nonStaticVar;
static void staticMethod() {
// Can access only staticVar
cout << "Static method" << endl;
}
void nonStaticMethod() {
// Can access both staticVar and nonStaticVar
cout << "Non-static method" << endl;
}
};
From this we conclude that static variables and methods are shared
by all instances of a class and belong to the class itself, while non-
static variables and methods belong to instances of the class and can
access both static and non-static variables.
4. Define class and object; write a simple Student class with
variables and methods; create an object.
ANS:
Class
A class in C++ is a blueprint or a template that defines the properties
and behavior of an object. It is a user-defined data type that
encapsulates data and functions that operate on that data.
Object
An object in C++ is an instance of a class. It has its own set of
attributes (data) and methods (functions) that are defined in the
class.
Student Class Example
Here's an example of a simple Student class with variables and
methods:
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
int age;
double grade;
public:
// Constructor
Student(string n, int a, double g) {
name = n;
age = a;
grade = g;
}
// Method to display student information
void displayInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Grade: " << grade << endl;
}
// Method to update student grade
void updateGrade(double newGrade) {
grade = newGrade;
}
};
int main() {
// Create an object of the Student class
Student student("John Doe", 20, 85.5);
// Call the displayInfo method
student.displayInfo();
// Update the student's grade
student.updateGrade(90.0);
// Call the displayInfo method again
cout << "Updated Information:" << endl;
student.displayInfo();
return 0;
}
In this example:
- We define a Student class with private variables name, age, and
grade.
- We define a constructor to initialize the student's information.
- We define two methods: displayInfo to display the student's
information and updateGrade to update the student's grade.
- We create an object student of the Student class and call its
methods to display and update the student's information.
OUTPUT:
Name: John Doe
Age: 20
Grade: 85.5
Updated Information:
Name: John Doe
Age: 20
Grade: 90
5. Explain default, parameterized, copy constructors and destructors
with examples and usage.
ANS:
DEFAULT CONSTRUCTOR
A default constructor is a constructor that takes no arguments. It is
called when an object is created without any arguments.
Eg:
#include<iostream>
using namespace std;
class A{
public:
};
int main() {
A obj;
return 0;
}
PARAMETERIZED CONSTRUCTOR
A parameterized constructor is a constructor that takes one or more
arguments. It is used to initialize objects with specific values.
Eg:
#include<iostream>
using namespace std;
class A{
public:
int val;
A(int x) {
val=x;
}
};
int main() {
A a(10);
cout<<a.val<<endl;
return 0;
}
COPY CONSTRUCTOR:
A copy constructor is a constructor that creates a copy of an existing
object. It is called when an object is passed by value to a function or
when an object is initialized with another object.
Eg:
#include<iostream>
using namespace std;
class A{
public:
int val;
A(int x) {
val=x;
}
};
int main() {
A a(10);
A a1=a;
cout<<a1.val<<endl;
return 0;
}
DESTRUCTOR
A destructor is a special member function that is called when an
object is about to be destroyed. It is used to release resources, such
as memory, that were allocated by the object.
Eg:
#include<iostream>
using namespace std;
class Car {
public:
car(string b, double e) {
brand=b;
engine=e;
cout<<”Constructor for car ”<<endl;
}
~ car() {
cout<<”Destructor”<<endl;
}
};
int main() {
car swift (“Suzuki”,1.2);
car copy = swift;
cout<<copy.brand<<endl;
return 0;
}
USAGES:
- Constructors are used to initialize objects with specific values.
- Destructors are used to release resources allocated by objects.
- Copy constructors are used to create copies of existing objects.
6. Discuss the significance of static variables and static methods in
C++. How are they different from instance members? Illustrate with
code.
ANS:
Significance of Static Variables
Static variables in C++ are shared by all instances of a class. They are
essentially global variables that are scoped to the class. The
significance of static variables includes:
- Sharing data: Static variables can be used to share data between all
instances of a class.
- Class-level data: Static variables are associated with the class itself,
rather than with any particular instance.
Significance of Static Methods
Static methods in C++ are methods that belong to the class itself,
rather than to any particular instance. The significance of static
methods includes:
- Utility functions: Static methods can be used to provide utility
functions that are related to the class, but do not require access to
instance data.
- Class-level operations: Static methods can perform operations that
are related to the class itself, rather than to any particular instance.
Differences from Instance Members
The main differences between static variables and methods and
instance members are:
- Scope: Static variables and methods are scoped to the class itself,
while instance members are scoped to individual instances.
- Sharing: Static variables are shared by all instances of a class, while
instance members are unique to each instance.
- Access: Static methods can only access static variables, while
instance methods can access both static and instance variables.
Code Example:
#include <iostream>
using namespace std;
class MyClass {
public:
static int staticVar; // Shared by all instances
int instanceVar; // Unique to each instance
static void staticMethod() {
// Belongs to the class itself
cout << "Static method called" << endl;
staticVar = 10; // Can access static variables
// instanceVar = 10; // Error: cannot access instance variables
}
void instanceMethod() { // Belongs to individual instances
cout << "Instance method called" << endl;
staticVar = 10; // Can access static variables
instanceVar = 10; // Can access instance variables
}
};
int MyClass::staticVar = 0; // Initialize static variable
int main() {
MyClass obj1;
MyClass obj2;
obj1.instanceVar = 5;
obj2.instanceVar = 10;
cout << "obj1.instanceVar: " << obj1.instanceVar << endl; //
Output: 5
cout << "obj2.instanceVar: " << obj2.instanceVar << endl; //
Output: 10
MyClass::staticVar = 5; // Access static variable through class name
cout << "MyClass::staticVar: " << MyClass::staticVar << endl; //
Output: 5
obj1.staticMethod(); // Call static method through instance
MyClass::staticMethod(); // Call static method through class name
return 0;
}
In this example, we define a class MyClass with static and instance
variables and methods. We demonstrate the differences between
static and instance members, including scope, sharing, and access.