Class Definition, Class Structure

Estudies4you
Q11. Define a class. Explain how classes are defined.
Answer: 

Class
A class is an abstract data type that groups the data and its associated functions. It can also hides the data and functions if required.
A class specification consists of two parts,
  1. Declaration of a class and class members
  2. Definitions of member functions of a class.
The members scope and types are described by the class declaration and the implementation of member functions are described by the class function definitions.
A class is defined using the key word class followed by name of the class. The class keyword indicates an abstract data type called name of the class. Body of class is defined inside the curly brackets and is terminated by semicolon at the end. Body of the class includes the variables and function declarations.
Syntax
class classname
{
private:
//Variables and function declarations
public:
//Variables and function declarations
};

Example
class Circle //Class Name
{
private:
int radius; //Variable Declaration
public:
void setdata( );
void getdata(int);
void display( ); //Member Function Declarations
void area( );
void perimeter( );
};

In the above example, class is a keyword and circle is the name of the class. The member variable radius is declared in private section and member functions are declared as public. Private ,public are the access modifiers that are used to provide access to the class members and are terminated by colon(:). The class is enclosed within curly braces and terminated by using a semicolon(;).

The variables that are declared in the private section are accessed only within the class or by the public member functions of the class. The methods that are available in the public section are accessible inside or outside the class by using objects.

The private variables in the class are directly accessible like public variables. This can be done by storing public and private variables in consecutive memory locations. The address of first member variable is stored in a pointer and pointer is incremented or decremented to access both private and public members directly.

When an object is created to the class, the address of variable in first memory location is stored in that object and by using that object also, private and public members are accessed directly.

To Top