Local object and global object in C++

In C++ objects can be classified as local object and global object.

Local object

A object defined inside a block is called local object.

A local object can be inside block or function or class

Local Object in C++ programming
Local Object in C++ programming

In above figure variable a and b are local variable inside complex class.

Inside main function Complex c=Complex(1,2); is defined here c is a complex object.

Example Local object declaration and use in main().

c is defined as local object since it is inside main function.

Example Local object example.

what is the lifetime of a local object

The local variable exists up to control is in block. When ever control goes out of block local variable destroyed.

Global Object

An object declared outside any class or method is known as global object.

Global Object in C++ programming
Global Object in C++ programming

C++Global object Example

Here object c is outside all class and method so it is a global object.

Example: Write a C++ program to show the difference between the local and global objects.


Local objects and global objects in C++ are used as per need. If the use of a variable is inside only a method or class then declare it local.

If a variable is required in various functions then make it global.

difference between global object and local object

Sr NoGlobal ObjectsLocal Objects
1Global objects are declared outside of all classes and methodsLocal Objects are declared inside any class, method, or block.
2Can be accessed by any class or method in the program.Can be accessed with in class, method or block where it is declared

Read More

  1. C++ program for student details
  2. Anonymous Object in C++
  3. Lowercase character to uppercase character
  4. Command Line Argument
  5. Local and Nested Classes in C++
  6. Arithmetic operations using switch case
  7. Switch Case in C Programming
  8. Constructor in C++
  9. Know more about C++
Categories C++