classes and objects - BCA, B.Tech_info

Easy way to learn

Tuesday, June 5, 2018

classes and objects

Class definition:

A class is a method in which the data and its related functions bind together. It allows the data and function to be hidden from external use, if necessary. The class declaration describe the type and scope of its member. The class declaration is almost similar to the structure declaration.

syntax:

class class_name
{
    private:
        variable declarations;
        function declarations;
    public:
       variable declarations;
       function declarations;
};

The body of class is enclosed within braces and terminated by a semicolon. The class body contain two sections, first one is private, and another one is public. These keywords are followed by a colon. The class body contain variable declaration and function declaration. These functions and variable are known as class members.
The class members that have been declared as private cannot be accessed by external function only can be accessed within class whereas public members can be accessed by outside the class also. External function only can access the public section of the class. 


Objects:

In C++, the class variables are known as objects. The declaration of an object is similar to that of a variable of any basic type.  The necessary memory space is allocated to an object at this stage.
Object can be created after the class definition.

syntax:

class record
{
       int a;
      int  b;
   public:
      int z;
};
   ….
   ….
record  i;
i.a=0;
i.b=10;
…….
…….

Here, objects a, b and c of type record. Objects can also be created when a class is defined by placing their names immediately after the closing brace.

syntax:

class record
{
      ….
      ….
} a, b, c;


Example program:

#include<iostream>

using namespace std;

class print
{
   private:
      int number;
   public:
      void input_value(void);
      void output_value(void);
};
void print::input_value(void)
{
   cout<<"\n Enter an integer \n";
   cin>> number;
}
void print::output_value(void)
{
    cout<<"Number entered is:"<<number;
}
int main()
{
print x;
x.input_value();
x.output_value();
return 0;
}

Output:

Enter an integer
12
Number entered is: 12

No comments:

Post a Comment

Polymorphism in C++