Exam Units
UNIT-1
Principles Of OOP
UNIT-2
Function, Class & Objects
UNIT-3
Constructor & Destructor
Important Comparison Tables
OOP vs POP Comparison
| Feature | OOP | POP |
|---|---|---|
| Approach | Bottom-up approach | Top-down approach |
| Program Structure | Objects and interactions | Functions that interact |
| Inheritance | Supported | Not supported |
| Access Control | Supported via access modifiers | Not supported |
| Encapsulation | Used to hide data | No data hiding; data is globally accessible |
| Security | Secure | Not secure |
| Examples | C++, Java, Python | C, BASIC, FORTRAN |
Access Specifiers Comparison
| public | private | protected | |
|---|---|---|---|
| Access in same class | ✅ | ✅ | ✅ |
| Access in derived class | ✅ | ❌ | ✅ |
| Access from objects | ✅ | ❌ | ❌ |
| Default specifier | Classes: ❌ Structs: ✅ |
Classes: ✅ | ❌ |
UNIT-1: Principles Of OOP
OOP stands for Object-Oriented Programming. It is a programming paradigm based on the concept of "objects", which are instances of classes. OOP emphasizes on objects rather than functions and makes the code flexible and modular. C++ is an object-oriented programming language that allows programmers to define their own data types and functions, called classes and objects respectively.
Applications of OOP include:
- Real-Time System design
- Hypertext and Hypermedia
- AI Expert System
- Office automation System
- Neural networking and parallel programming
- Stimulation and modeling system
- CIM/CAD/CAM systems
Advantages:
- Code can be reused multiple times using classes
- Inherit classes to subclasses for data redundancy
- Easy to maintain and modify
- Maintains data security
- Low-cost development
Disadvantages:
- Size is larger than other programs
- Slower than other programs
- Not suitable for some sorts of problems
The main differences between OOP and POP are:
| Feature | OOP | POP |
|---|---|---|
| Approach | Bottom-up approach | Top-down approach |
| Program Structure | Program divided into objects and their interactions | Program divided into functions that interact |
| Inheritance | Supported | Not supported |
| Access Control | Supported via access modifiers | Not supported |
| Examples | C++, Java, Python | C, BASIC, FORTRAN |
The basic concepts of C++ are:
- Object: Any entity that has state and behavior. In C++, an object is an instance of a class.
- Class: A user-defined data type that encapsulates data and functions into a single entity.
- Data Encapsulation: Binding code and data together into a single unit, providing data security.
- Data Abstraction: Hiding internal details and showing only functionality.
- Inheritance: When one object acquires all properties and behaviors of a parent object, providing code reusability.
- Polymorphism: One task performed in different ways (function overloading or operator overloading).
- Dynamic binding: Decision made at runtime regarding which code to run (late binding).
- Message passing: Objects communicate with each other by sending and receiving information through member functions.
The structure of a C++ program consists of the following sections:
- Documentation Section: Contains comments about the program logic (optional).
- Link Section: Contains header files (#include) and namespaces (using namespace std;).
- Definition Section: Used to declare constants and define user-defined data types.
- Global Declaration Section: Variables and class definitions declared as global.
- Function Definition Section: Contains user-defined functions.
- Main Function: Starting point of program execution.
Example:
#includeusing namespace std; int main(){ cout<<"Hello World!"; return 0; } // Output: Hello World!
User-Defined Data Types:
- Structure: Collection of logically related data items of different data types grouped together. Example:
struct Student { int id; char name[20]; }; - Class: Template that specifies fields and methods of objects. Example:
class Student { int id; string name; }; - Union: Like a structure, but elements share common memory.
- Enumeration: User-defined type with named constants. Example:
enum day {mon, tue, wed};
Derived Data Types:
- Arrays: Fixed-size collection of elements of same type.
- Functions: Group of statements combined for a specific purpose.
- Pointers: Special variable containing address of another variable.
A variable is a name of a memory location used to store data. Its value can be changed and it can be reused many times. It is a way to represent memory location through a symbol so that it can be easily identified.
Syntax: datatype variable_name;
Example: int a;
A reference variable is an alias or second name for an existing variable. It refers to the address of another variable and represents the name of another variable, location, or value. Once initialized, the variable can be referred to using either the original name or the reference name.
Syntax: data_type &reference_name = existing_variable;
Example:
#includeusing namespace std; int main() { int a = 10; int &value = a; cout << value; // Output: 10 return 0; }
Variable Declaration: Variables must be declared before use. It specifies the data type and name of the variable.
Syntax:
- Single variable:
type variable_name; - Multiple variables:
type var1, var2, var3;
Examples:
int a = 50, b = 100;float f = 50.8;char c = 'Z';
Dynamic Initialization: Initializing a variable at runtime during its declaration.
Example:
#includeusing namespace std; int main() { int a; cout << "Enter Value of a: "; cin >> a; int cube = a * a * a; // Dynamically initialized return 0; }
The scope resolution operator (::) is used to reference global variables or member functions that are out of scope. It accesses hidden variables or functions in a program.
Uses:
- Access global variables when a local variable has the same name
- Define member functions outside of a class
- Access static variables and functions of a class
- Override functions in inheritance
Example:
#includeusing namespace std; int num = 50; // Global variable int main() { int num = 100; // Local variable cout << "Local variable: " << num << endl; cout << "Global variable: " << ::num; // Using scope resolution return 0; } // Output: Local variable: 100 // Global variable: 50
In C++, access specifiers determine the accessibility of class members:
- Public: Members can be accessed from anywhere, both inside and outside the class. Used to represent the interface of the class.
- Private: Members can only be accessed from within the class. Used to represent the implementation and hide data from the outside world.
- Protected: Members can be accessed from within the class and its derived classes. Used when implementation should be accessible to derived classes.
Example:
class MyClass {
public:
int x; // Accessible anywhere
private:
int y; // Only accessible within class
protected:
int z; // Accessible in class and derived classes
};
int main() {
MyClass myObj;
myObj.x = 25; // OK
myObj.y = 50; // Error: y is private
return 0;
}
UNIT-2: Function, Class & Objects
A function is a block of code that performs a specific operation. It can take input parameters and optionally return a value.
Function Prototype: Provides the compiler with a description of a function before it's defined. It includes return type, function name, and parameter types.
Example: int sum(int, int);
Function Declaration: Tells the compiler about a function name and how to call it. The actual body can be defined separately.
Syntax: return_type function_name(parameter list);
Function Calling: Invoking a function by its name with appropriate arguments. Control is passed to the function, which executes and may return a value.
Syntax: variable = function_name(arg1, arg2, ..., argn);
Example: result = sum(num1, num2);
An inline function is a function that is expanded in line when called. The entire code of the inline function is inserted at the point of the function call during compilation, which can increase efficiency for small functions.
Syntax:
inline return-type function-name(parameters)
{
// function code
}
Implementation:
If a function is defined entirely within the class specification (typically in the header file), it is automatically considered inline.
Example:
#includeusing namespace std; inline int cube(int s) { return s * s * s; } int main() { cout << "The cube of 2 is: " << cube(2); return 0; } // Output: The cube of 2 is: 8
Default Arguments: Values provided in a function declaration that are automatically assigned by the compiler if the calling function doesn't provide a value for that argument. If a value is passed, the default value is overridden.
Example:
#includeusing namespace std; int sum(int x, int y, int z = 0, int w = 0) { return (x + y + z + w); } int main() { cout << sum(10, 20) << endl; // Output: 30 cout << sum(10, 20, 30) << endl; // Output: 60 cout << sum(10, 20, 30, 50) << endl; // Output: 110 return 0; }
Constant Arguments: Arguments that cannot be modified by the function. Useful when passing by reference to prevent accidental modification.
Example:
#includeusing namespace std; class Test { int value; public: Test(int v = 0) { value = v; } int get() const { // const member function return value; } }; int main() { Test t(20); cout << t.get(); return 0; } // Output: 20
Function overloading is a feature where two or more functions have the same name but different parameters (different types or number of arguments). The compiler differentiates between overloaded functions based on their parameters.
Rules:
- Function name must be the same
- Parameters must be different (type or number)
- Return type alone cannot differentiate functions
Advantage: Increases code readability as you can use the same name for similar operations.
Example:
#includeusing namespace std; class Cal { public: int add(int a, int b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } }; int main() { Cal c; cout << c.add(10, 20) << endl; // Output: 30 cout << c.add(12, 20, 23) << endl; // Output: 55 return 0; }
Class: A class is a user-defined data type that acts as a blueprint for creating objects. It combines data representation and methods for manipulating that data into a single package. A class specifies the form of an object and can have fields, methods, constructors, etc.
Syntax:
class className
{
// data members and member functions
};
Object: An object is a single instance of a class. When a class is defined, only the specification is created; memory is allocated when an object is created. Objects can access the data and functions defined in the class.
Syntax: className objectVariableName;
An instance of a class is an object created from that class at runtime using one of the available constructors. It represents a specific realization of the class with its own set of attribute values and state.
When you create an instance of a class, you are creating a unique object that has its own data values and can perform the actions defined by the class's methods. Each instance is independent and can have different attribute values.
Example: If "Car" is a class with attributes like color, model, and year, then "myCar" would be an instance of the Car class with specific values for these attributes.
Member Function: A member function of a class is a function that has its definition or prototype within the class definition. It operates on objects of the class and has access to all members of the class for that object. Member functions are also known as methods and encapsulate the behaviors that objects of the class can perform.
Nesting of Member Functions: When a member function calls another member function of the same class, it is referred to as nesting of member functions. This allows for modular code organization within a class.
Example:
#includeusing namespace std; class Average { int a, b; public: void read() { cout << "Enter a and b: "; cin >> a >> b; } void print() { cout << "Value of a: " << a << endl; cout << "Value of b: " << b << endl; cout << "Average is: " << avg() << endl; } int avg() { return (a + b) / 2; } }; int main() { Average a; a.read(); a.print(); return 0; }
A private member function is a function declared in the private section of a class. It can only be accessed and called from within the class itself, typically through public member functions.
Private member functions are used for internal operations or helper functions that should not be directly accessible from outside the class. They help encapsulate implementation details, hide complexity, and ensure proper data protection.
Characteristics:
- Accessible only within the class
- Cannot be called from outside the class or by other objects
- Used for internal processing and helper operations
- Contributes to data security and encapsulation
A friend function in C++ is a function that is not a member of a class but has access to the class's private and protected data members. It is declared inside the class with the friend keyword, but defined outside the class scope.
Properties:
- Not a member function of the class
- Can access private and protected members of the class
- Declared with
friendkeyword inside the class - Defined outside the class like a normal function
Example:
#includeusing namespace std; class Test { private: int a; public: friend void show(Test t); }; void show(Test t) { cout << "Enter a: "; cin >> t.a; cout << "Value of a: " << t.a; } int main() { Test t1; show(t1); return 0; }
UNIT-3: Constructor & Destructor
A constructor is a special member function in C++ that is automatically invoked when an object is created. It has the same name as the class and is used to initialize the data members of the object.
Properties:
- Same name as the class
- No return type (not even void)
- Automatically called when object is created
- Can be overloaded
- Cannot be inherited
Example:
#includeusing namespace std; class Person { string name; int age; public: Person() { // Default constructor name = "Unknown"; age = 0; cout << "Default constructor called." << endl; } void displayInfo() { cout << "Name: " << name << endl; cout << "Age: " << age << endl; } }; int main() { Person person1; // Constructor called automatically person1.displayInfo(); return 0; }
A default constructor is a constructor that has no parameters. It is invoked automatically when an object is created without any arguments. If the programmer does not define a default constructor, the compiler provides an implicit default constructor.
Example:
#includeusing namespace std; class Employee { public: Employee() { cout << "Default Constructor Invoked" << endl; } }; int main() { Employee e1; // Calls default constructor Employee e2; // Calls default constructor return 0; } // Output: // Default Constructor Invoked // Default Constructor Invoked
A copy constructor initializes an object using another object of the same class. It is used to:
- Initialize one object from another of the same type
- Copy an object to pass it as an argument to a function
- Copy an object to return it from a function
If not defined, the compiler provides a default copy constructor. However, for classes with pointer variables or dynamic memory, a user-defined copy constructor is necessary.
Testing Copy Constructor:
#includeusing namespace std; class A { public: int x; A(int a) { // Parameterized constructor x = a; } A(A& i) { // Copy constructor x = i.x; } }; int main() { A a1(20); // Calls parameterized constructor A a2(a1); // Calls copy constructor cout << a2.x; // Output: 20 return 0; }
A parameterized constructor is a constructor that accepts parameters. It is used to initialize objects with specific values provided during object creation, allowing for flexible and customized object initialization.
Key Points:
- Has parameters in its declaration
- Allows initialization with specific values
- Provides flexibility in object creation
- Can be overloaded with different parameter sets
Example:
#includeusing namespace std; class Employee { public: int id; string name; float salary; Employee(int i, string n, float s) { id = i; name = n; salary = s; } void display() { cout << id << " " << name << " " << salary << endl; } }; int main() { Employee e1(101, "Sonoo", 890000); Employee e2(102, "Nakul", 59000); e1.display(); e2.display(); return 0; } // Output: // 101 Sonoo 890000 // 102 Nakul 59000
The characteristics of constructors are:
- The name of the constructor is the same as its class name.
- Constructors are mostly declared in the public section of the class (though they can be in private).
- Constructors do not return values; hence they do not have a return type.
- A constructor gets called automatically when we create an object of the class.
- Constructors can be overloaded (multiple constructors with different parameters).
- Constructor cannot be declared virtual.
- Constructor cannot be inherited by derived classes.
- Addresses of constructors cannot be referred (no pointer to constructor).
- Constructors make implicit calls to new and delete operators during memory allocation.
#includeusing namespace std; class Student { public: int id; string name; float salary; // Parameterized constructor Student(int i, string n, float s) { id = i; name = n; salary = s; } void display() { cout << "ID: " << id << ", Name: " << name << ", Salary: " << salary << endl; } }; int main() { // Creating objects with parameters passed to constructor Student e1(101, "Sonoo", 890000); Student e2(102, "Nakul", 59000); e1.display(); e2.display(); return 0; } // Output: // ID: 101, Name: Sonoo, Salary: 890000 // ID: 102, Name: Nakul, Salary: 59000
Key Concepts Cheatsheet
Encapsulation
Bundling data with methods operating on that data
Inheritance
Creating hierarchical relationships between classes
Polymorphism
Same methods performing different actions
Abstraction
Hiding complex details, showing only essentials