Unit 1.
Principles of Object oriented Programming
Procedural-Oriented Programming (POP) and Object-Oriented Programming (OOP)
are two distinct programming paradigms with fundamental differences in how they
structure and organize code.
Procedural-Oriented Programming (POP):
Focus:
POP emphasizes procedures or functions as the primary building blocks. Programs
are typically structured as a sequence of instructions or function calls that operate
on data.
Approach:
It follows a top-down approach, breaking down a large problem into smaller,
manageable functions that are executed sequentially.
Data Handling:
Data is often global and can be accessed and modified by any function, which can
lead to issues with data security and maintainability in larger programs.
Examples:
Languages like C, Pascal, and FORTRAN are examples of procedural languages.
Object-Oriented Programming (OOP):
Focus:
OOP centers around objects, which encapsulate both data (attributes) and the
functions (methods) that operate on that data.
Approach:
It follows a bottom-up approach, building programs from independent, self-
contained objects that interact with each other.
Data Handling:
OOP emphasizes data hiding and encapsulation, where data within an object is
protected and can only be accessed through its defined methods, enhancing data
security and integrity.
Key Concepts:
OOP incorporates concepts like inheritance (reusing code), polymorphism (allowing
objects of different classes to be treated as objects of a common type), and
abstraction (hiding complex implementation details).
Examples:
Languages like C++, Java, Python, and C# are examples of object-oriented
languages.
Unit 1. Principles of Object oriented Programming
Difference between OOP and POP:
OOP POP
Object oriented. Structure oriented.
Program is divided into objects. Program is divided into functions.
Bottom-up approach. Top-down approach.
Inheritance property is used. Inheritance is not allowed.
It uses access specifier. It doesn't use access specifier.
Encapsulation is used to hide the data. No data hiding.
Concept of virtual function. No virtual function.
Object functions are linked through Parts of program are linked through
message passing. parameter passing.
Expanding new data and functions is not
Adding new data and functions is easy
easy.
The existing code can be reused. No code reusability.
use for solving big problems. Not suitable for solving big problems.
C++, Java. C, Pascal.
Unit 1. Principles of Object oriented Programming
Features of OOP (Object Oriented Programming):-
1. Class
2. Object
3. Encapsulation
4. Data Abstraction
5. Inheritance
6. Polymorphism
7. Data binding
8. Message Passing
Application of Object Oriented Programming:-
User interface design such as windows, menu
Real Time Systems such as Control system for cars, aircraft, space
vehicles etc
Office automation system such as Document Management System i.e.
Word processing system, spread sheet software etc
AI and Expert System
Neural Networks and parallel programming System
Decision support system etc
Advantages of OOP:-
1. Improved software-development productivity:
Object-oriented programming is modular, as it provides separation of
duties in object-based program development. It is also extensible, as
objects can be extended to include new attributes and behaviors. Objects
can also be reused within an across applications. Because of these three
factors – modularity, extensibility, and reusability – object-oriented
programming provides improved software-development productivity over
traditional procedure-based programming techniques.
2. Improved software maintainability:
Since the design is modular, part of the system can be updated in case of
issues without a need to make large-scale changes.
3. Faster development:
Reuse enables faster development. Object-oriented programming
languages come with rich libraries of objects, and code developed during
projects is also reusable in future projects.
Unit 1. Principles of Object oriented Programming
4. Lower cost of development:
The reuse of software also lowers the cost of development. Typically,
more effort is put into the object-oriented analysis and design, which
lowers the overall cost of development.
5. Higher-quality software:
Faster development of software and lower cost of development allows
more time and resources to be used in the verification of the software.
Although quality is dependent upon the experience of the teams, object
oriented programming tends to result in higher-quality software.
The main features of object
oriented programming are
as follows:
Classes
Objects
Abstraction
Polymorphism
Inheritance
Encapsulation
In the upcoming sections, let’s see
each object-oriented
programming feature in detail.
Classes and Objects
A class is a template that consists of the data members or variables and functions
and defines the properties and methods for a group of objects.
The compiler does not allocate memory whenever you define a class.
Example:
You can define a class called Vehicle. Its data fields can be vehicle_name,
model_number, color, date_of_manufacture, etc.
An object is nothing but an instance of a class. Each object has its values for the
different properties present in its class. The compiler allocates memory for each
object.
Example:
The different objects of the class Vehicle can be Car, Bike, Bicycle, etc. Each of
them will have its values for the fields like color, model_number, etc.
Unit 1. Principles of Object oriented Programming
Abstraction
The literal meaning of abstraction is to remove some characteristics from something
to reduce it to a smaller set. Similarly, Object Oriented Programming abstraction
exposes only the essential information of an object to the user and hides the other
details.
In real life, like when you toggle a switch, it simply turns on or off the lights. Here, we
only know the functionality of the switch, but we don’t know its internal
implementation, like how it works.
How to implement abstraction?
You can implement abstraction using classes that group the data members and
function together. Inside classes, you can choose the access specifiers for its
members to control how they are visible to the outside world. We can also create
header files containing the implementations of all the necessary functions. So, you
can include the header file and call these functions without getting into their
implementation.
Example:
You can have a parent class called “Shape” and other classes like Square, Circle,
Rectangle, etc. Since all these are also shapes, they will have all the properties of a
shape so that they can inherit the class Shape.
Polymorphism
The word polymorphism means to have many forms. So, by using polymorphism,
you can add different meanings to a single component.
There are two types of polymorphism:
Run-time polymorphism
Compile-time polymorphism
Let's see each type in the next section.
Method Overloading
Methods overloading is a type of compile-time polymorphism using which you can
define various functions with the same name but different numbers of arguments.
The function call is resolved at compile time, so it's a type of compile-time
polymorphism. Here resolution of the function call implies binding to the correct
function definition depending on the arguments passed in the function call.
Example:
You can create a function “add”. Now, when you pass two integers to this function, it
will return their sum, while on passing two strings, it will return their concatenation.
So, the same function acts differently depending on the input data type.
Method Overriding
Method Overriding is a type of run-time polymorphism. It allows overriding a parent
class’s method by a child class. Overriding means that a child class provides a new
implementation of the same method it inherits from the parent class.
These function calls are resolved at run-time, so it's a type of runtime polymorphism.
Example:
You can have a parent class called “Shape” with a method named “findArea” that
calculates and returns the area of the shape. Several sub-classes inherit from the
Unit 1. Principles of Object oriented Programming
“Shape,” like Square, Circle, Rectangle, etc. Each of them will define the function
“findArea” in its way, thus overriding the function.
Encapsulation
Encapsulation means enclosing the data/variables and the methods for manipulating
the data into a single entity called a class. It helps to hide the internal implementation
of the functions and state of the variables, promoting abstraction.
Example:
You can have some private variables in a class that you can't access outside the
class for security reasons. Now, to read or change the value of this variable, you can
define public functions in the class which will perform the read or writes operations.
Know What is Object in OOPs here in detail.
Dynamic Binding
Dynamic binding takes place during run time based on the type of object. Since it is
delayed till the run time, it is also called late binding or runtime binding. When the
compiler cannot determine all the information required to resolve a function call
during compile time, these function calls are not bound until run time.
Message Passing
Message passing refers to the process of passing a message, or data, between
different objects or components in a program. This can be done in many ways, such
as function calls, events, or inter-process communication. The specific
implementation of message passing will depend on the program's design and the
system's needs.
DATA TYPE IN C++ :
C++ categorizes data types into three main groups: Primitive (or Built-in), Derived,
and User-Defined. The basic data types in C++ primarily refer to the Primitive Data
Types, which are fundamental and directly available for use.
Here are the basic (primitive) data types in C++:
Integer Types:
int:Used to store whole numbers (integers) without decimal points. Its size and
range can vary by system, but it's typically 4 bytes.
short: A smaller integer type, typically 2 bytes.
long: A larger integer type, often 4 or 8 bytes.
long long: An even larger integer type, typically 8 bytes.
These can also be signed (default, allowing positive and negative values)
or unsigned (only non-negative values).
Floating-Point Types:
float: Used for single-precision floating-point numbers (numbers with decimal
points). Typically 4 bytes.
Unit 1. Principles of Object oriented Programming
double: Used for double-precision floating-point numbers, offering higher precision
than float. Typically 8 bytes.
long double:Offers even higher precision, size can vary.
Character Types:
char: Used to store a single character (e.g., 'a', 'Z', '5'). Typically 1 byte.
wchar_t: Used for wide characters, which can represent a broader range of
characters (like Unicode). Its size can be 2 or 4 bytes.
Boolean Type:
bool: Used to store logical values, either true or false. Typically 1 byte.
Void Type:
void: Represents the absence of a type. It's used in specific contexts, such as
indicating that a function does not return a value or for generic pointers.
TYPE COMPATABILITY
In C++, type compatibility refers to the ability to use two different data types
together in an operation, such as an assignment or an expression, without
requiring explicit type conversion. This allows for flexibility in coding while
maintaining type safety.
Key aspects of type compatibility in C++:
Implicit Type Conversion (Coercion):
Assignment Compatibility:
Expression Compatibility:
Parameter Compatibility:
DECLARATION OF VARIABLE
In C++, declaring a variable involves specifying its data type and a unique name
(identifier). This process reserves a portion of memory for storing a value of that
specific type.
SYNTAX : data_type variable_name;
Explanation:
data_type:
This specifies the type of data the variable will hold (e.g., int for integers, float for
floating-point numbers, char for characters, bool for boolean
values, std::string for strings).
Unit 1. Principles of Object oriented Programming
variable_name:
This is the unique name you assign to the variable, which will be used to refer to it
throughout your program. Variable names must follow specific rules (e.g., start with
a letter or underscore, no spaces or special characters, case-sensitive).
Dynamic Initialization of Variable:
Dynamic initialization of variables in C++ refers to the process where the initial
value of a variable is determined and assigned at runtime, rather than at compile
time. This is in contrast to static initialization, where the value is known and set
when the program is compiled.
#include <iostream>
using namespace std;
int main() {
int x;
cout << "Enter a number: ";
cin >> x;
int square = x * x; // dynamically initialized using runtime value
cout << "Square: " << square << endl;
return 0;
}
Referances veriable:
In C++, a reference variable is an alias, or an alternative name, for an existing
variable. It provides a way to access the original variable through a different
name, effectively allowing you to manipulate the original variable indirectly.
Key characteristics of C++ reference variables:
Declaration and Initialization: References are declared using the ampersand (&)
symbol and must be initialized at the time of declaration with an existing variable.
int original_var = 10;
int &ref_var = original_var; // ref_var is now an alias for original_var
Type casting:
Type casting in C++ is the process of converting a variable from one data type to
another. This conversion can be done either implicitly by the compiler or explicitly by
the programmer.
1. Implicit Type Conversion (Coercion):
This occurs automatically when the compiler converts compatible data types without
explicit instructions from the programmer. For example, assigning an int to
a float or performing arithmetic operations between different numeric types.
Unit 1. Principles of Object oriented Programming
int num_int = 10;
float num_float = num_int; // Implicit conversion from int to float
2. Explicit Type Casting:
This requires the programmer to explicitly instruct the compiler to perform the
conversion using a cast operator. C++ offers several explicit cast operators:
double value = 3.14;
int int_value = (int)value; // C-style cast
EX:
#include <iostream>
using namespace std;
int main() {
int i = 10;
char c = 'A'; // Two variables of different type
cout << (int)c << endl; // printing c after manually converting it
int sum = i + c; // Adding i and c,
cout << sum; // Printing sum
return 0;
}
Special Operator in C++:
1. Scope Resolution Operator:
In C++, the scope resolution operator (::) is used to access the identifiers such
as variable names and function names defined inside some other scope in the
current scope.
Ex:
#include <iostream>
using namespace std;
int x = 3; // Global x
int main()
{
int x = 10; // Local x
cout << ::x; // Printing the global variable x
return 0;
}
Unit 1. Principles of Object oriented Programming
Memory Management Operators:
In C++, dynamic memory management primarily relies on two
operators: new and delete. These operators allow for the allocation and
deallocation of memory on the heap during program execution.
new operator:
The new operator is used to dynamically allocate memory for a variable, an array, or
an object on the heap.
It returns a pointer to the newly allocated memory.
Syntax for a single object: data_type* pointer_variable = new data_type;
Syntax for an array: data_type* pointer_variable = new data_type[size];
The allocated memory can optionally be initialized during allocation. For
example: int* p = new int(7);
delete operator:
The delete operator is used to deallocate memory that was previously allocated
using the new operator.
It takes a pointer to the allocated memory as an argument.
Syntax for a single object: delete pointer_variable;
Syntax for an array: delete[] pointer_variable;
Failing to delete allocated memory can lead to memory leaks, where memory
remains occupied even after it's no longer needed, reducing available system
resources.
Manipulators :
In C++, manipulators are functions or objects used with the insertion (<<) and
extraction (>>) operators to modify the formatting of input and output streams. They
are primarily used to control how data is displayed on the screen or in files, affecting
aspects like field width, alignment, precision, and base representation .
Unit 1. Principles of Object oriented Programming
STRUCTURE OF C++ PROGRAM
The C++ program is written using a specific template structure. The
structure of the program written in C++ language is as follows:
Documentation Section:
This section comes first and is used to document the logic of the
program that the programmer going to code.
It can be also used to write for purpose of the program.
Whatever written in the documentation section is the comment and is
not compiled by the compiler.
Documentation Section is optional since the program can execute
without them. Below is the snippet of the same:
/* This is a C++ program to find the
factorial of a number
The basic requirement for writing this
program is to have knowledge of loops
To find the factorial of number
iterate over range from number to one
*/
Linking Section:
The linking section contains two parts:
Header Files:
Generally, a program includes various programming elements like built-
in functions, classes, keywords, constants, operators, etc. that are
already defined in the standard C++ library.
In order to use such pre-defined elements in a program, an appropriate
header must be included in the program.
Unit 1. Principles of Object oriented Programming
Standard headers are specified in a program through the preprocessor
directive #include. In Figure, the iostream header is used. When the
compiler processes the instruction #include<iostream>, it includes the
contents of the stream in the program. This enables the programmer to
use standard input, output, and error facilities that are provided only
through the standard streams defined in <iostream>. These standard
streams process data as a stream of characters, that is, data is read
and displayed in a continuous flow. The standard streams defined in
<iostream> are listed here.
#include<iostream>
Namespaces:
A namespace permits grouping of various entities like
classes, objects, functions, and various C++ tokens, etc. under a single
name.
Any user can create separate namespaces of its own and can use
them in any other program.
In the below snippets, namespace std contains declarations for cout,
cin, endl, etc. statements.
using namespace std;
Namespaces can be accessed in multiple ways:
o using namespace std;
o using std :: cout;
Definition Section:
It is used to declare some constants and assign them some value.
In this section, anyone can define your own datatype using primitive
data types.
In #define is a compiler directive which tells the compiler whenever
the message is found to replace it with “Factorial\n”.
typedef int INTEGER; this statement tells the compiler that whenever
you will encounter INTEGER replace it by int and as you have declared
INTEGER as datatype you cannot use it as an identifier.
Global Declaration Section:
Here, the variables and the class definitions which are going to be
used in the program are declared to make them global.
The scope of the variable declared in this section lasts until the entire
program terminates.
These variables are accessible within the user-defined functions also.
Function Declaration Section:
It contains all the functions which our main functions need.
Usually, this section contains the User-defined functions.
This part of the program can be written after the main function but for
this, write the function prototype in this section for the function which
for you are going to write code after the main function.
// Function to implement the
// factorial of number num
Unit 1. Principles of Object oriented Programming
INTEGER factorial(INTEGER num)
{
// Iterate over the loop from
// num to one
for (INTEGER i = 1; i <= num; i++) {
fact *= i;
}
// Return the factorial calculated
return fact;
}
Main Function:
The main function tells the compiler where to start the execution of the
program. The execution of the program starts with the main function.
All the statements that are to be executed are written in the main
function.
The compiler executes all the instructions which are written in the curly
braces {} which encloses the body of the main function.
Once all instructions from the main function are executed, control
comes out of the main function and the program terminates and no
further execution occur.
Below is the program to illustrate this:
// Documentation Section
/* This is a C++ program to find the
factorial of a number
The basic requirement for writing this
program is to have knowledge of loops
To find the factorial of a number
iterate over the range from number to 1
*/
#include <iostream> // Linking Section
using namespace std;
#define msg "FACTORIAL\n" // Definition Section
Unit 1. Principles of Object oriented Programming
typedef int INTEGER;
INTEGER num = 0, fact = 1, storeFactorial = 0; // Global Declaration Section
INTEGER factorial(INTEGER num) // Function Section
{
for (INTEGER i = 1; i <= num; i++) // Iterate over the loop from
{
fact *= i; // num to one
}
return fact; // Return the factorial
INTEGER main( ) // Main Function
{
INTEGER Num = 5; // Given number Num
storeFactorial = factorial(Num); // Function Call
cout << msg;
cout << Num << "! = " // Print the factorial
<< storeFactorial << endl;
return 0;
}
Output
FACTORIAL
5! = 120
Basic Input / Output in C++
Input Operators and Functions:
Extraction Operator (>>):
This operator is used with the cin object (standard input stream, typically the
keyboard) to read data from the input stream and store it in a variable.
Example: cin >> variableName;
getline() function:
Unit 1. Principles of Object oriented Programming
Used to read an entire line of text, including spaces, until a newline character is
encountered.
Syntax: getline(cin, stringVariable);
get() function:
Used to read a single character from the input stream. It can also be used to read a
specified number of characters into a character array.
Example: char ch = cin.get();
Output Operators and Functions:
Insertion Operator (<<):
This operator is used with the cout object (standard output stream, typically the
screen) to display data on the console.
Example: cout << "Hello, world!"; or cout << variableName;
put() function:
Used to write a single character to the output stream.
Example: cout.put('A');
Standard I/O Objects:
cin: The standard input stream object, an instance of the istream class.
cout: The standard output stream object, an instance of the ostream class.
cerr:The standard unbuffered error stream object, an instance of the ostream class,
used for immediate error messages.
clog:The standard buffered error stream object, an instance of the ostream class,
used for logging messages that might be buffered before output.
Example of Basic I/O:
C++
#include <iostream> // Required for cin and cout
int main() {
int age;
std::string name;
// Input using extraction operator
std::cout << "Enter your age: ";
std::cin >> age;
// Clear the buffer after reading an integer before reading a string
with spaces
std::cin.ignore();
// Input using getline()
std::cout << "Enter your full name: ";
std::getline(std::cin, name);
// Output using insertion operator
std::cout << "Hello, " << name << "! You are " << age << " years old."
Unit 1. Principles of Object oriented Programming
<< std::endl;
return 0;
}
simple c++ programs
1. Hello World Program:
This program prints "Hello, World!" to the console. It is the classic first program for
learning any language.
#include <iostream> // Includes the input/output stream library
int main() // Main function where program execution begins
{
std::cout << "Hello, World!" << std::endl; // Prints the string to the console
return 0; // Indicates successful program execution
}
2. Sum of Two Numbers:
This program takes two integer inputs from the user and calculates their sum.
#include <iostream>
int main() {
int num1, num2, sum; // Declare integer variables
std::cout << "Enter first number: ";
std::cin >> num1; // Read first number from user
std::cout << "Enter second number: ";
std::cin >> num2; // Read second number from user
sum = num1 + num2; // Calculate the sum
std::cout << "Sum: " << sum << std::endl; // Print the sum
return 0; }
3. Check Even or Odd:
This program determines whether a given integer is even or odd.
#include <iostream>
int main()
{
int num;
std::cout << "Enter an integer: ";
std::cin >> num;
Unit 1. Principles of Object oriented Programming
if (num % 2 == 0)
{ // Check if the remainder when divided by 2 is 0
std::cout << num << " is an even number." << std::endl;
}
else
{
std::cout << num << " is an odd number." << std::endl;
}
return 0;
}
CLASS AND OBJECT:
In C++, classes and objects are fundamental concepts of Object-Oriented
Programming (OOP).
Class:
A class is a user-defined data type that serves as a blueprint or a template
for creating objects. It defines the structure and behavior that its objects will
possess. A class encapsulates data members (variables) that represent the
state of an object and member functions (methods) that define the actions
or operations an object can perform.
Example of a C++ Class:
class Car
{
public: // Access specifier
std::string brand;
std::string model; // Data members
int year;
void displayInfo() // Member function
{
// Code to display car information
}
};
Object:
An object is an instance of a class. It is a real-world entity created from the blueprint
defined by a class. When an object is created, memory is allocated for its data
members, and it can then interact with the member functions defined in its
class. Multiple objects can be created from a single class, each with its own set of
data, but all sharing the same defined behaviors.
Unit 1. Principles of Object oriented Programming
Example of C++ Object Creation:
Car myCar; // Creating objects of the Car class
Car yourCar;
In this example, myCar and yourCar are distinct objects of the Car class. Each
object will have its own brand, model, and year values, and both can utilize
the displayInfo() member function.
Access Specifier in C++
access specifiers are keywords used within class definitions to control the visibility
and accessibility of class members (data members and member functions). They are
crucial for implementing encapsulation and data hiding, core principles of object-
oriented programming.
There are three primary access specifiers in C++:
public:
Members declared under the public specifier are accessible from anywhere in the
program, both within and outside the class.
They form the public interface of the class, allowing other parts of the program to
interact with objects of that class.
private:
Members declared under the private specifier are only accessible from within the
class in which they are declared.
They cannot be accessed directly from outside the class, including by derived
classes.
This specifier is primarily used for data hiding, ensuring that the internal state of an
object can only be manipulated through its public interface.
protected:
Members declared under the protected specifier are accessible within the class
itself and by classes that inherit from it (derived classes).
They are not accessible directly from outside the class or by unrelated classes.
This specifier is specifically designed to support controlled access in inheritance
hierarchies.
Default Access Specifier:
If no access specifier is explicitly provided for class members, they are by
default considered private.
Unit 1. Principles of Object oriented Programming
Defining member function : Inside and Outside the class
There are two ways to define a procedure or function that belongs to a class:
Inside Class Definition
Outside Class Definition
1. Inside Class Definition
The member function is defined inside the class definition it can be defined directly.
Similar to accessing a data member in the class we can also access the public
member functions through the class object using the dot operator (.).
Syntax:
class_name{
public:
return_type Method_name() // method inside class definition
{
// body of member function
}
};
// C++ program for Inside Class Definition
#include <iostream>
using namespace std;
class rectangle {
private:
int length;
int breadth;
public:
rectangle(int length, int breadth) // Constructor
{
this->length = length; // this pointer
this->breadth = breadth;
}
int area() { return (length * breadth); } // area() function inside class
int perimeter() { return 2 * (length + breadth); } // perimeter() function outside class
};
int main() {
rectangle r(2, 3); // Creating object
cout << "perimeter: " << r.perimeter() << endl;
cout << "area: " << r.area() << endl;
return 0;
}
Unit 1. Principles of Object oriented Programming
2. Outside Class Definition
The member function is defined outside the class definition it can be defined using
the scope resolution operator. Similar to accessing a data member in the class we
can also access the public member functions through the class object using the dot
operator (.).
Syntax:
class Class_name
{
public:
return_type Method_name(); // method outside class definition
};
return_type Class_name :: Method_name()// Outside the Class using
scope resolution operator
{
// body of member function
}
Example: In the following code, a rectangle class, in which member function area()
and member function perimeter() is defined outside the class by using the scope
resolution operator.
// C++ program for Outside the Class Definition
#include <iostream>
using namespace std;
class rectangle {
private:
int length;
int breadth;
public:
rectangle(int length, int breadth) // Constructor
{
this->length = length; // this pointer
this->breadth = breadth;
}
int area(); // area() function defined outside the class
int perimeter(); // perimeter() function defined outside the class
};
// function defining using scope resolution operator "::"
int rectangle::area() { return (length * breadth); }
int rectangle::perimeter()
{
return 2 * (length + breadth);
}
Unit 1. Principles of Object oriented Programming
int main()
{
// Creating object
rectangle r(2, 3);
cout << "perimeter: " << r.perimeter() << endl;
cout << "area: " << r.area() << endl;
return 0;
}
C++ Objects:
When a class is defined, only the specification (attributes and behaviour) for the object is
defined. No memory is allocated to the class definition. To use the data and access
functions defined in the class, we need to create its objects.
Objects are the actual entities that are created as an instance of a class. There can be as
many objects of a class as desired. For example, in the above, we discussed the class
of Cars. If we create an actual car based on the properties of the Car class, the car we
made is the object of that class.
Create Object : Once the class is defined, we can create its object in the same way we
declare the variables of any other inbuilt data type.
className objectName;
This statement creates an object of className class.
Member Access : Members of the class can be accessed inside the class itself
simply by using their assigned name.
To access them outside, the (.) dot operatoris used with the object of the class.
obj.member1 // For data members
obj.member2(..) // For functions
Class Object
A blueprint or template for creating An instance of a class with
objects. actual values.
No memory is allocated for a class Memory is allocated when an
until an object is created. object is created.
Conceptual entity describing A real-world entity created from
structure and behaviour. the class.
Class vs Object
The following table lists the primary differences between the classes and
objects in C++:
Unit 1. Principles of Object oriented Programming
Stores specific data and
Defines properties and functions
manipulates it using class
common to all objects of that type.
functions.
Represents a general concept or Represents a specific instance
type. of the class.
Objects Memory Allocation
Objects Memory Allocation in C++
The way memory is allocated to variables and functions of the class is different even
though they both are from the same class. The memory is only allocated to the
variables of the class when the object is created.
The memory is not allocated to the variables when the class is declared. At the same
time, single variables can have different values for different objects, so every object
has an individual copy of all the variables of the class. But the memory is allocated to
the function only once when the class is declared. So the objects don’t have
individual copies of functions; only one copy is shared among each object.
Static Data Members in C++
When a static data member is created, there is only a single copy of the data
member which is shared between all the objects of the class. Usually, every object
has an individual copy of the attributes unless specified statically.
Static members are not defined by any object of the class. They are exclusively
defined outside any function using the scope resolution operator.