Classes and Objects: C++ 6 Sem, A' Div 2018-19 Ms. Mouna M. Naravani
Classes and Objects: C++ 6 Sem, A' Div 2018-19 Ms. Mouna M. Naravani
C++
6th Sem, ‘A’ Div
2018-19
Ms. Mouna M. Naravani
C Structures Revisited
Limitations of C Structure
1. struct complex Where as, this is perfectly ok…
{
c3.x = c1.x + c2.x
float x;
c3.y = c1.y + c2.y
float y;
};
struct complex c1, c2, c3;
c3 = c1 + c2 // This is illegal in C.
Limitations contd….
2. Structures do not permit data hiding. Structure members can be directly accessed by
structure variables by any functions anywhere in their scope.
That is, by default, the members of the structure are public.
• Class is a way to bind the data and its associated functions together(Encapsulation).
• Class function definitions - describes how the class functions are implemented.
The general form of class declaration:
Data members
and Member
functions are
collectively called
Class Members.
Terminated by ;
• Class members are usually grouped under two sections, private and public.
• private and public are keywords.
• These are known as visibility labels.
• NOTE: these keywords are followed by a colon(:).
• The class members that have been declared as public can be accessed from outside the
class.
• On the other hand, private members can be accessed only from within the class.
• The data hiding (using private declaration) is the key feature of OOP.
• By default, the members of a class are private.
Data hiding in classes
Defining member functions
• This label tells the compiler which class the function belongs to.
• The membership label class-name:: tells the compiler that the function
function-name belongs to the class class-name.
• The symbol :: is called the scope resolution operator.
Characteristics of Member functions:
• Several different classes can use the same function name. The ‘membership
label’ will resolve their scope.
• Member functions can access the private data of the class. A non-member
function cannot do so.
• A Member function can call another Member function directly, without
using dot operator.
When the memory is allocated?
Memory Allocation for Objects
➢ Memory space for objects is allocated when they are declared and not when the class is
specified.
➢ Since all the objects belonging to that class use the same member functions, no
separate space is allocated for member functions when the objects are created.
➢ Only space for data members is allocated separately for each object.
➢ Separate memory locations for the objects are essential, because the member variables
will hold different data values for different objects.
Creating Objects
• Once a class has been declared, we can create objects of that type by
using class name.
demo d;
d.x=10; //error
d.Z = 16; //OK