Classes, Objects and Memory
Classes, Objects and Memory
Memory
• Declaration of a class does not allocate
memory to the class data members.
• Declaration of an object reserves memory for
data members only and not for member
functions.
• Member functions are created and memory is
allocated to them only once when a class is
declared.
Static member variables
• Like a function, single data member can be
created for the entire class using keyword
‘static’.
• When a variable is declared as static it is
initialised to zero
• A static function or data element is only
recognised inside the scope of the present
class
Example -program
• Class – static member variable
• Class- difference b/w static and non-static
Static member function
• Static member function can access only static
member variables and functions of the same
class.
• Static member function declared in the public
section can be invoked using its class name
without using its object (possible to invoke
through objects also).
• Static member function can also be private
invoked by public static member function
Example-program
• Class – Static member function
• Class-private static member function
• Class-Public static member variable
Static object
• Initialize all data member variable of a class to
zero
• If the object is static we need not initialize each
member variable to zero
• Constructor: Initialize member variable of the
object to desired value.
• Advantage: The declaration of static object
remove garbage of its data member and initialize
them to zero.
Example - program
• Class-static objects
Array of objects
• It is possible to create objects using arrays.
Example-Program
• class - array of objects
Copy constructor
• Constructor can accept arguments of a data
type and also an object of its own class.
• It requires one argument, with reference to an
object of that class.
Application:
• Any runtime allocation of the resource like file
handling, a network connection.
Example-Program
• copy constructor
Destructor
• Special member function like constructor
• Class name preceded by a tilde
• Destroys the class object created by
constructors
Example- Program
• Destructors