Image

C++ - Class - Class

Class

In C++, class is a way which binds data member and its associates function together within a single unit.

Any variables declare within a class are called data members, any functions declare within a class are called members functions. By default anything declare within a class are private. It is a basic fundamental unit of object oriented programming.

Syntax:
	class <class_name>
	{
	private:
		      data members 
		       and
		      member function
	public:
		      data members 
		       and
		      member function
	protected:
		       data members 
		       and
		       member function
	};
e.g:
class Person
	{
	private:
		int pid;
		char name[10]	
	public:
		void setData(){
		}
	};
Ex: Function inside the class
#include<conio.h>
#include<iostream.h>
class Item
{
    private:
	int item_one,n;
	float price;

    public:
       void setitem()
		{

		  cout<<"enter no \n" ;
		  cin>>n;
		 }
     void show()
	 {
	   cout<<"item_one="<item_one;
	   cout<<"price="<price;
	   }
      };
       void main()
      {
	Item i;
	i.setitem();
	i.show();
	getch();
	}
Function outside the class
#include<iostream.h>
#include<conio.h>
class Student
{
  private:
        	char name[10];
    		int age;
  		long int dob;
    		char mob_no[10];

  public:
  		void getdata();
  		void display();
};

void Student:: getdata()
{
cout<<"enter the name of student"<<endl;
cin>>name;
cout<<"enter the age of student"<<endl;
cin>>age;
cout<<"enter the dob of student"<<endl;
cin>>dob;
cout<<"enter the mob_no of student"<<endl;
cin>>mob_no;
}
void Student:: display()
{
cout<<"\nname of student="<<name;
cout<<"\nage of student="<<age;
cout<<"\ndob of student="<<dob;
cout<<"\nmob_no of student="<<mob_no;
}

 void main()
  {
  clrscr();
    Student obj;
    obj.getdata();
    obj.display();
    getch();
  }