Module 2 - 1 - Classes and Objects
Module 2 - 1 - Classes and Objects
C Structure revisited
Structure – Method of packing together data of different types
a group of logically related data items
a user-defined data type with a template that serves to define its data properties
can create variables of that type using declarations similar to built in types.
struct student
{
char name[20]; /*the keyword struct declares student as a new data type that holds three
int roll_number; fields. These elements inside the structure body are called the structure
char prog[20]; elements or members. The identifier student is called structure name and
}; is used to create variables of type student*/
• They do not allow data hiding. Structure members can be directly accessed by
structure variables by any function anywhere in their scope.
Extensions to structures in C++
• It brings user defined types as close as possible to built in data types
• It provides facility to hide the data.
• Inheritance is also supported
student std;
C++ incorporates all these extensions in another user defined type known as class
Ie., there is only slight difference between structure and class in C++
• The only difference is that by default, the members of a class are private and in a structure it is
public
Specifying a class
• Class is a way to bind data and functions together.
• It allows data and functions to be hidden
• Class specification has two parts: -
1. Class declaration
2. Class function definition
class_name variable_name;
Example:
student s;
• we can create any number of objects belonging to that class by declaring more than one
object in one statement.
This statement are written in main().
• The objects can also be defined by placing their name immediately after the closing brace of
the class.
Accessing class members
The private data of a class can be accessed only through the member functions of that class
Syntax: -
Objectname.functionname(actual arguments)
Eg. x.getdata(10,20);
But if the data is declared public
x.qty=10; is possible
Thank You