Home | | Object Oriented Programming | Object Creation and Destruction

Chapter: Object Oriented Programming(OOP) : Basic Characteristics of OOP

Object Creation and Destruction

Classes are the object oriented Programing constructs which are Out of data types.





      Classes are the object oriented Programing constructs which are Out of data types.


      Defining variables of a class is



Called a class specification and

Such variables are called objects.


      A class encloses both data and functions that operate on the data. These are called data members and member functions.


      Classes are basic constructs of C++ for creating user defined data types.


      Classes are extension of structures.


      Difference is - all members of a structure are public by default where as all members of a class are private by default.


      The property of C++ which allows association of data and functions in to a single unit called encapsulation.


Defining variables of a class type is known as a CLASS INSTANTIATION and such variables are called OBJECTS.


An object is an instance of a class.


The necessary resources are created when the class is instantiated. The class specifies the type and scope of its members.


The members are usually grouped under two sections – private and public. Private members are accessible only to their own class members.


Public members are accessible from outside the class also.


Syntax of defining a class : class class_name



body of the class



§    Here class is the keyword and body has declaration of variables and functions


The variables and functions enclosed in a class are called data members and member functions respectively.


A class should be given a meaningful name.


The name of data and member functions of a class can be same as those in other classes. A class can have multiple functions with the same name.


But it cannot have multiple variables with same name.


Class objects


A class specification only declares the structure of objects and it must be instantiated in order to make use of the services provided by it.


The syntax


Similar to structure variable objects can also be created by placing their names immediately after the closing braces like in the example below…..


class student


….} c1, c2, c3;


OR class student





student c1, c2, c3;


2. Accessing class members


Class members can be accessed using the objects. Objects must use member access operator, the dot(.) Syntax




Data Member can be variable or function. Should be public to be accessible. objectName.function_Name( actual parameters)


Ex: s1.name; // cannot be accessed -> data hiding if private S1.gatdata();


class student



int roll;

char *name; public:

void setdata(int r_no, char *name1)


{ roll=r_no; name=name1; }




void main(){ student s1;


s1.setdata(1, “Abhishek”);



The object accessing its class members resembles a client-server model. A client seeks a service


A server provides services requested by a client. Class – like a server


Objects – like clients

In typical case, the process is as follows:

§                 calculate the size of an object - the size is mostly the same as that of the class but can vary. When the object in question is not derived from a class, but from a prototype instead, the size of an object is usually that of the internal data structure (a hash for instance) that holds its slots.


§                 allocation - allocating memory space with the size of an object plus the growth later, if possible to know in advance


§                 binding methods - this is usually either left to the class of the object, or is resolved at dispatch time, but nevertheless it is possible that some object models bind methods at creation time.


§                 calling an initializing code (namely, constructor) of superclass

Those tasks can be completed at once but are sometimes left unfinished and the order of the tasks can vary and can cause several strange behaviors. For example, in multi-inheritance, which initializing code should be called first is a difficult question to answer. However, superclass

constructors should be called before subclass constructors.

It is a complex problem to create each object as an element of an array.[further explanation needed] Some languages (e.g. C++) leave this to programmers.


Handling exceptions in the midst of creation of an object is particularly problematic because usually the implementation of throwing exceptions relies on valid object states. For instance, there is no way to allocate a new space for an exception object when the allocation of an object failed before that due to a lack of free space on the memory. Due to this, implementations of OO languages should provide mechanisms to allow raising exceptions even when there is short supply of resources, and programmers or the type system should ensure that their code is exception-safe. Note that propagating an exception is likely to free resources (rather than allocate them). However, in object oriented programming, object construction may always fail, because constructing an object should establish the class invariants, which are often not valid for every combination of constructor arguments. Thus, constructors can always raise exceptions.


The abstract factory pattern is a way to decouple a particular implementation of an object from code for the creation of such an object.


3. Creation methods


The way to create objects varies across languages. In some class-based languages, a special method known as a constructor, is responsible for validating the state of an object. Just like ordinary methods, constructors can be overloaded in order to make it so that an object can be


created with different attributes specified. Also, the constructor is the only place to set the state of immutable objects[Wrong clarification needed]. A copy constructor is a constructor which takes a


(single) parameter of an existing object of the same type as the constructor's class, and returns a copy of the object sent as a parameter.


Other programming languages, such as  Objective-C, have class methods, which can

include constructor-type methods, but are not restricted to merely instantiating objects.


C++ and Java have been criticized[by whom?] for not providing named constructors—a constructor must always have the same name as the class. This can be problematic if the programmer wants to provide two constructors with the same argument types, e.g., to create a point object either from the cartesian coordinates or from the polar coordinates, both of which would be represented by two floating point numbers. Objective-C can circumvent this problem, in that the programmer can create a Point class, with initialization methods, for example, +newPointWithX:andY:, and +newPointWithR:andTheta:. In C++, something similar can be done using static member functions.


A constructor can also refer to a function which is used to create a value of a tagged union, particularly in functional languages.


4. Object destruction


It is generally the case that after an object is used, it is removed from memory to make room for other programs or objects to take that object's place. However, if there is sufficient memory or a program has a short run time, object destruction may not occur, memory simply being deallocated at process termination. In some cases object destruction simply consists of deallocating the memory, particularly in garbage-collected languages, or if the "object" is actually a plain old data structure. In other cases some work is performed prior to deallocation, particularly destroying member objects (in manual memory management), or deleting references from the object to other objects to decrement reference counts (in reference counting). This may be automatic, or a special destruction method may be called on the object.


In class-based OOLs with deterministic object lifetime, notably C++, a destructor is a method called when an instance of a class is deleted, before the memory is deallocated. Note that in C++, destructors differs from constructors in various ways: it cannot be overloaded, it has to have no arguments, it does not need to maintain class invariants, and exceptions that escape a destructor cause program termination.


In garbage collecting languages, objects may be destroyed when they can no longer be reached by the running code. In class-based GCed languages, the analog of destructors are finalizers, which are called before an object is garbage-collected. These differ in running at an unpredictable time and in an unpredictable order, since garbage collection is unpredictable, and are significantly less-used and less complex than C++ destructors. Example of such languages include Java, Python, and Ruby.


Destroying an object will cause any references to the object to become invalid, and in manual memory management any existing references become dangling references. In garbage collection (both tracing garbage collection and reference counting), objects are only destroyed when there are no references to them, but finalization may create new references to the object, and to prevent dangling references, object resurrection occurs so the references remain valid.


Examples class Foo



// This is the prototype of the constructors public:


Foo(int x);


Foo(int x, int y); // Overloaded Constructor

Foo(const Foo &old); // Copy Constructor ~Foo(); // Destructor




Foo::Foo(int x)


//  This is the implementation of

//  the one-argument constructor



Foo::Foo(int x, int y)



//  This is the implementation of

//  the two-argument constructor



Foo::Foo(const Foo &old)


//  This is the implementation of

//  the copy constructor





// This is the implementation of the destructor




int main()


Foo foo(14); // call first constructor


Foo foo2(12, 16); // call overloaded constructor

Foo foo3(foo); // call the copy constructor


return 0;

//  destructors called in backwards-order

//  here, automatically

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Object Oriented Programming(OOP) : Basic Characteristics of OOP : Object Creation and Destruction |

Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.