Defining Class and Object in C++

Defining Class and Object in C++

A class is composed of data members (variables) and member functions or both. We need to specify the access specifier (public, private or protected) of the members of the class. The access specifier must be followed by a colon (:)

The syntax to define a class is as below.

class className
{
access-specifier:
data-type var1;
data-type var2;

return-type function1(parameters);
return-type function2(parameters);

}object1, object2, …;

In the above syntax, class is a keyword followed by the name of the class. The className may be any legal identifier. A class must have a starting and closing curly bracket. The body of the class is written between these two curly brackets.

A class is composed of data members (variables) and member functions or both. We need to specify the access specifier (public, private or protected) of the members of the class. The access specifier must be followed by a colon (:)

Data members are declared along with their relative data types. A class may have one or more than one data members as needed.

Like data members, a class may have one or more than member functions. There are two ways to declare member functions. The detail will be discussed in the coming tutorial.

A class is closed by right curly bracket followed by a semicolon. The objects of the class may be declared immediately after closing the class definition followed by a semicolon or may be declared later.

Look at the following example to see how a class and objects are defined.

Example

class Person
{
public:
string name;
int age;
void speak();

}p1,p2;

In above example:

class name is Person
access specifier is public
data members are name and age
member function is speak()
objects are p1,p2

Another way of defining objects are as below.

void main()
{
Person p1, p2;
}

It is important to note that object of a class can access all the data members or member functions of a class (unless not encapsulated). Every object of a class has its own set of data members declared in a class and may be used to store different values related to that specific object only.

More Related Articles For You

    C++ Tutorial

    C++ Quizzes

 

Search

Shortcodes Ultimate

 
Follow Us
 
BGP