Note:
* A class can be local as well as global.
* Global class: when the definition of the class is given outside the functions then it is a global class.
* When the class is global then the objects can be local as well as global.
* Local class: when the definition of the class is given within the function then it is a local class.
* When the class is local then we can have only local objects.
Example of local class.
#include <iostream> #include<conio.h> using namespace std; int main() { class student { private: int roll; char name[20]; float age; public: void read() { cout<<"Enter roll,name and age "; cin>>roll>>name>>age; } void show() { cout<<"roll "<<roll<<" name "<<name<<" age "<<age<<endl; } }; student s; s.read(); s.show(); return(0); }
/* Output */ Enter roll,name and age 101 Amit 15 roll 101 name Amit age 15
Question:7
C++ program to declare a class named student with attributes as roll,name,m1,m2,m3,total and per. Take input for the details , calculate and display total and per.
Sol:
#include <iostream> #include<conio.h> using namespace std; class student { private: int roll; char name[20]; float m1,m2,m3,total,per; public: void read(); void cal(); void show(); }; void student::read() { cout<<"Enter roll,name, m1,m2 and m3 "; cin>>roll>>name>>m1>>m2>>m3; } void student::cal() { total=m1+m2+m3; per=total/3; } void student::show() { cal(); cout<<"roll "<<roll<<" name "<<name<<" Total "<<total<<" per "<<per<<endl; } int main() { student s; s.read(); s.show(); return(0); }
/* Output */ Enter roll,name, m1,m2 and m3 101 Amit 98 95 97 roll 101 name Amit Total 290 per 96.6667
Note:
When a member function is called from within another member function it is known as “nesting of member function”.
Note:
Can we give (the definition of) member function in private?
Sol: Yes,if required the member functions can be given in private,
(i). in such situation the definition of member has to be given in private.
(ii). And such member functions cannot be called/invoked from outside the class, rather it has to be invoked/called from within another member function.
Question:8
C++ program to declare a class named student with attributes as roll,name,m1,m2,m3,total and per. Take input for the details , calculate and display total and per. (member function in private)
Sol:
#include <iostream> #include<conio.h> using namespace std; class student { private: int roll; char name[20]; float m1,m2,m3,total,per; void cal() { total=m1+m2+m3; per=total/3; } public: void read(); void show(); }; void student::read() { cout<<"Enter roll,name, m1,m2 and m3 "; cin>>roll>>name>>m1>>m2>>m3; } void student::show() { cal(); cout<<"roll "<<roll<<" name "<<name<<" Total "<<total<<" per "<<per<<endl; } int main() { student s; s.read(); s.show(); return(0); }
/* Output */ Enter roll,name, m1,m2 and m3 102 Sumit 98 97 99 roll 102 name Sumit Total 294 per 98