1) Define an Object.
Explain the relationship between a class and
its object. ?
Ans ) An object in object-oriented programming (OOP) is an instance
of a class. It is a self-contained unit that consists of both data
(attributes) and methods (functions or procedures) that operate on the
data. An object represents an entity with specific characteristics and
behaviors, modeled after real-world concepts or abstract ideas.
For example, if you have a class called Car, an object of that class
could be a specific car like "Toyota Corolla," which will have
attributes such as color, model, and speed, and methods such as
accelerate() or brake().
Relationship Between a Class and Its Object:
Class: A class is a blueprint or template for creating objects. It defines
the structure and behavior that the objects created from the class will
have. A class specifies the attributes (also called properties or fields)
and methods (functions or actions) that objects will possess.
Object: An object is an instance of a class, meaning that it is a
concrete realization of the class. When a class is defined, no memory
is allocated until an object of that class is created.
Example:
#include <iostream>
using namespace std;
// Define the class 'Car'
class Car {
// Data members (attributes)
public:
string brand;
string model;
int year;
// Member function (method)
void displayInfo() {
cout << "Car Brand: " << brand << endl;
cout << "Car Model: " << model << endl;
cout << "Car Year: " << year << endl;
}
};
int main() {
// Creating an object of class 'Car'
Car myCar;
// Setting attributes (data members) for the object
myCar.brand = "Toyota";
myCar.model = "Corolla";
myCar.year = 2022;
// Calling a member function using the object
myCar.displayInfo();
return 0;
}
Output
Car Brand: Toyota
Car Model: Corolla
Car Year: 2022
2 ) Explain about Inline functions with simple example ?
Ans ) An inline function is a function where the compiler attempts to
insert the code of the function directly at the place where the function
is called, rather than performing a regular function call. The primary
advantage of inline functions is to improve performance by
eliminating the overhead of a function call (such as pushing
arguments onto the stack, jumping to the function code, and
returning).
How Inline Functions Work:
When you declare a function as inline, the compiler replaces the
function call with the function's code, effectively "inlining" the code
at the point of the call. This can improve performance in cases where
the function is small and called frequently.
Syntax for Inline Function in C++:
inline return_type function_name(parameters) {
// function body
}
Example:
#include <iostream>
using namespace std;
// Declare the inline function
inline int square(int x) {
return x * x;
}
int main() {
int num = 5;
// Call the inline function
int result = square(num);
cout << "The square of " << num << " is " << result << endl;
return 0;
}
3 ) What is static data member ? Explain with example ?
Ans ) A static data member is a variable that is shared by all objects
of a class. It is not tied to any specific instance of the class. Unlike
regular data members that each object of the class gets its own copy
of, a static data member has only one copy, no matter how many
objects of the class are created.
Key Points About Static Data Members:
Shared Among All Objects: All instances (objects) of the class share
the same static data member. Any change to the static data member is
reflected across all instances.
Only One Copy: Static data members are not duplicated for each
object; there is only one copy for the entire class.
Accessed Using Class Name: Static data members can be accessed
using the class name (though they can also be accessed through
objects).
Memory Allocation: Static data members are allocated memory only
once, and the memory is shared by all instances of the class.
Must Be Defined Outside the Class: While you declare a static data
member inside the class, it must be defined outside the class to
allocate memory.
Syntax for Static Data Member:
class ClassName {
public:
static data_type member_name; // Static data member declaration
};
#include <iostream>
using namespace std;
class MyClass {
public:
// Declare static data member
static int count;
// Constructor
MyClass() {
count++; // Increment the static data member on object creation
}
// Method to display the current value of the static data member
void displayCount() {
cout << "Object Count: " << count << endl;
}
};
// Define the static data member outside the class
int MyClass::count = 0;
int main() {
MyClass obj1; // First object, count will be 1
obj1.displayCount();
MyClass obj2; // Second object, count will be 2
obj2.displayCount();
MyClass obj3; // Third object, count will be 3
obj3.displayCount();
// Accessing the static data member without creating an object
cout << "Accessing static count directly: " << MyClass::count <<
endl;
return 0;
}
Output
Object Count: 1
Object Count: 2
Object Count: 3
Accessing static count directly: 3
4 ) Explain with an example pointer to objects ?
Ans ) A pointer to an object in C++ is a pointer that holds the memory
address of an object. This allows you to dynamically access and
manipulate the object's members via the pointer.
How Pointer to Objects Works:
Object: A regular object in C++ is created using a class, and it resides
in the stack memory.
Pointer to an Object: A pointer is created using the * symbol and can
store the memory address of an object. The pointer can then be used
to access the object’s attributes and methods.
ClassName *pointer_name;
#include <iostream>
using namespace std;
// Define the class 'Person'
class Person {
public:
string name;
int age;
// Constructor to initialize the object
Person(string n, int a) {
name = n;
age = a;
}
// Method to display information
void displayInfo() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
// Creating an object of Person class
Person person1("John", 30);
// Declaring a pointer to the object
Person *ptr = &person1; // Pointer pointing to the address of
person1
// Accessing members of the object using the pointer
cout << "Using pointer to access object members:" << endl;
ptr->displayInfo(); // Using the arrow operator to call the method
// Accessing object attributes using the pointer
cout << "Name: " << ptr->name << ", Age: " << ptr->age << endl;
return 0;
}
Output
Using pointer to access object members:
Name: John, Age: 30
Name: John, Age: 30
5 ) What is the purpose of copy constructor ? with example
Ans ) A copy constructor in C++ is a special constructor used to
create a new object as a copy of an existing object. It is primarily used
in situations where a new object is initialized with an existing object,
such as:
When an object is passed by value to a function.
When an object is returned by value from a function.
When an object is explicitly copied using assignment or initialization.
The main purpose of a copy constructor is to ensure that the new
object has the same data as the original object while ensuring proper
handling of dynamic memory allocation (if necessary).
ClassName obj2 = obj1; // Calls copy constructor
#include <iostream>
using namespace std;
class Box {
public:
int length;
// Default constructor
Box(int l) {
length = l;
cout << "Constructor called! Length: " << length << endl;
}
// Copy constructor
Box(const Box &b) {
length = b.length; // Copying the value of length from the
original object
cout << "Copy constructor called! Length: " << length << endl;
}
// Method to display the value of length
void display() {
cout << "Length: " << length << endl;
}
};
int main() {
Box box1(10); // Constructor is called
Box box2 = box1; // Copy constructor is called
box1.display();
box2.display();
return 0;
}
Constructor called! Length: 10
Copy constructor called! Length: 10
Length: 10
Length: 10
6 ) Write about dynamic memory allocation operators ?
Ans ) In C++, dynamic memory allocation refers to allocating
memory at runtime (during the execution of the program), as opposed
to static memory allocation, where the memory is allocated at compile
time. Dynamic memory allocation allows for more flexible memory
usage because memory is allocated only when needed and can be
freed when no longer required.
C++ provides two main operators for dynamic memory allocation:
new: Allocates memory on the heap.
delete: Deallocates memory previously allocated by new.
#include <iostream>
using namespace std;
int main() {
// 1. Using 'new' to allocate memory for a single integer
int* ptr = new int; // Dynamically allocated memory for one
integer
// Assign a value to the allocated memory
*ptr = 10;
cout << "Value stored in dynamically allocated memory: " << *ptr
<< endl;
// 2. Using 'new[]' to allocate memory for an array of integers
int size = 5;
int* arr = new int[size]; // Dynamically allocate memory for an
array of 5 integers
// Assign values to the array elements
for (int i = 0; i < size; ++i) {
arr[i] = i * 2; // Assigning values (0, 2, 4, 6, 8)
}
cout << "Array elements: ";
for (int i = 0; i < size; ++i) {
cout << arr[i] << " "; // Printing values of the array
}
cout << endl;
// 3. Using 'delete' to deallocate memory for a single object
delete ptr; // Freeing memory allocated for the single integer
// 4. Using 'delete[]' to deallocate memory for an array
delete[] arr; // Freeing memory allocated for the array
return 0;
}
Output
Value stored in dynamically allocated memory: 10
Array elements: 0 2 4 6 8
7 ) Discuss in detail the basic concepts of Object oriented
programming ?
Object-Oriented Programming (OOP) is a programming paradigm
that is centered around the concept of "objects." An object is an
instance of a class, and a class is a blueprint for creating objects. The
primary goal of OOP is to design and structure software in a way that
is modular, reusable, and easier to maintain.
1. Classes and Objects
Class:
A class is a blueprint or template for creating objects. It defines the
properties (data members) and behaviors (methods or functions) that
the objects of the class will have.
Example:
cpp
Copy
class Car {
public:
string model;
int year;
void start() {
cout << "Car is starting" << endl;
}
};
Object:
An object is an instance of a class. When we create an object from a
class, it gets its own copies of the data members and methods defined
in the class.
Example of creating an object:
cpp
Copy
Car car1; // 'car1' is an object of the 'Car' class
car1.model = "Toyota";
car1.year = 2022;
car1.start();
2. Encapsulation
Encapsulation is the concept of bundling data (variables) and methods
(functions) that operate on the data into a single unit called a class.
This ensures that the internal state of the object is hidden from the
outside world, and only specific methods can access and modify that
state.
Access Modifiers:
Private: Data members and methods declared as private cannot be
accessed from outside the class.
Public: Data members and methods declared as public can be
accessed from anywhere in the program.
class BankAccount {
private:
double balance; // Private data member
public:
void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
double getBalance() {
return balance;
}
};
3. Inheritance
Inheritance allows a class (called a derived class) to inherit properties
and behaviors (data members and methods) from another class (called
the base class). This helps in reusing code and creating hierarchical
relationships.
Example:
cpp
Copy
class Animal {
public:
void eat() {
cout << "Animal is eating" << endl;
}
};
class Dog : public Animal {
public:
void bark() {
cout << "Dog is barking" << endl;
}
};
int main() {
Dog d;
d.eat(); // Inherited method from Animal
d.bark(); // Method from Dog class
}
In this example, Dog inherits from Animal, meaning Dog can use all
the functions of Animal, like eat(), in addition to its own bark()
function.
4. Polymorphism
Polymorphism means "many forms" and refers to the ability of a
function, method, or operator to behave in different ways depending
on the object it is acting on. It allows one interface to be used for
different underlying forms (data types).
Types of Polymorphism:
Compile-Time Polymorphism (Method Overloading, Operator
Overloading): The function to be called is determined at compile
time.
Run-Time Polymorphism (Method Overriding): The function to be
called is determined at runtime.
Example (Method Overloading):
cpp
Copy
class Math {
public:
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
};
Example (Method Overriding):
cpp
Copy
class Shape {
public:
virtual void draw() {
cout << "Drawing Shape" << endl;
}
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing Circle" << endl;
}
};
int main() {
Shape* shape = new Circle();
shape->draw(); // Will call the Circle's draw() method (run-time
polymorphism)
}
5. Abstraction
Abstraction is the concept of hiding the complex implementation
details and showing only the necessary functionality to the user. It is
achieved by using abstract classes and interfaces in OOP.
An abstract class is a class that cannot be instantiated (i.e., you cannot
create objects of this class directly). It can have abstract methods
(methods without a body), which must be implemented by the derived
classes.
Example:
cpp
Copy
class Shape {
public:
virtual void draw() = 0; // Pure virtual function (abstract method)
};
class Circle : public Shape {
public:
void draw() override {
cout << "Drawing Circle" << endl;
}
};
Summary of OOP Concepts:
Classes and Objects: A class is a blueprint for creating objects, and an
object is an instance of a class.
Encapsulation: The bundling of data and methods, with controlled
access to the data through access modifiers.
Inheritance: The ability of a class to inherit properties and behaviors
from another class, promoting code reuse.
Polymorphism: The ability to use the same method name for different
behaviors (e.g., method overloading and method overriding).
Abstraction: Hiding the implementation details and showing only
essential features of an object.
10 )
#include <iostream>
using namespace std;
int main() {
// Declare a single-dimensional array
int arr[] = {10, 20, 30, 40, 50};
// Declare a pointer that will point to an integer
int *ptr;
// Make the pointer point to the first element of the array
ptr = arr;
// Output elements using pointer arithmetic
cout << "Array elements using pointer:" << endl;
for (int i = 0; i < 5; i++) {
// Pointer dereferencing to access the array elements
cout << *(ptr + i) << " "; // *(ptr + i) is equivalent to arr[i]
}
// Output the array using array index
cout << "\nArray elements using array indexing:" << endl;
for (int i = 0; i < 5; i++) {
cout << arr[i] << " "; // Accessing array elements directly
}
return 0;
}
Output
Array elements using pointer:
10 20 30 40 50
Array elements using array indexing:
10 20 30 40 50
Key Concepts:
Pointer: A pointer is a variable that stores the memory address of
another variable.
Single-Dimensional Array: A single-dimensional array is a collection
of elements stored in contiguous memory locations. Each element is
accessible by its index.
8 ) Explain how a friend function acts as a bridge between 2 classes
with an example ?
Ans ) A friend function in C++ is a function that is not a member of a
class but is allowed to access the private and protected members of
the class. It acts as a "bridge" between two or more classes by
enabling them to interact with each other's private data without
making the data public.
How a friend function works as a bridge:
Access to Private Members: A friend function can access the private
and protected members of a class.
Encapsulation Preservation: Even though the friend function has
access to private data, the data itself remains encapsulated and not
exposed to the outside world.
Interaction Between Classes: Friend functions can help classes
interact or share data without directly exposing their internals to each
other.
#include <iostream>
using namespace std;
class ClassB; // Forward declaration of ClassB
class ClassA {
private:
int valueA;
public:
ClassA(int val) : valueA(val) {}
// Declare the friend function
friend void display(ClassA, ClassB);
};
class ClassB {
private:
int valueB;
public:
ClassB(int val) : valueB(val) {}
// Declare the friend function
friend void display(ClassA, ClassB);
};
// Friend function definition that accesses private data of both classes
void display(ClassA a, ClassB b) {
cout << "ClassA value: " << a.valueA << endl;
cout << "ClassB value: " << b.valueB << endl;
}
int main() {
ClassA objA(10);
ClassB objB(20);
// Call the friend function
display(objA, objB);
return 0;
}
Output
ClassA value: 10
ClassB value: 20
9 ) Discuss about the different types of constructors with examples ?
Ans )
Default Constructor
Parameterized Constructor
Copy Constructor
1. Default Constructor
A default constructor is a constructor that takes no parameters. It is
automatically called when an object is created without passing any
arguments.
Example :
#include <iostream>
using namespace std;
class MyClass {
public:
int value;
// Default constructor
MyClass() {
value = 0; // Initialize value to 0
}
void display() {
cout << "Value: " << value << endl;
}
};
int main() {
MyClass obj; // Calls default constructor
obj.display(); // Output: Value: 0
return 0;
}
2. Parameterized Constructor
A parameterized constructor allows you to initialize an object with
specific values at the time of its creation. It takes one or more
arguments.
#include <iostream>
using namespace std;
class MyClass {
public:
int value;
// Parameterized constructor
MyClass(int v) {
value = v; // Initialize value with the passed argument
}
void display() {
cout << "Value: " << value << endl;
}
};
int main() {
MyClass obj(10); // Calls parameterized constructor with value 10
obj.display(); // Output: Value: 10
return 0;
}
3. Copy Constructor
A copy constructor is used to create a new object as a copy of an
existing object. It takes a reference to an object of the same class as its
argument.
#include <iostream>
using namespace std;
class MyClass {
public:
int value;
// Parameterized constructor
MyClass(int v) {
value = v;
}
// Copy constructor
MyClass(const MyClass &obj) {
value = obj.value; // Initialize value with the value of the
existing object
}
void display() {
cout << "Value: " << value << endl;
}
};
int main() {
MyClass obj1(10); // Calls parameterized constructor
MyClass obj2 = obj1; // Calls copy constructor
obj2.display(); // Output: Value: 10
return 0;
}