New and delete with classes
Using Normal object
student s1;
In order to invoke a member function using a normal object we use “.” (dot operator),
Example:
student s1;
s1.read();
s1.show();
Using pointer type object
student *p=new student;
whereas in order to invoke a member function using pointer type object we use “->” (arrow operator).
example:
student *p=new student;
p->read();
p->show();
Example:1
Write a C++ program to declare a class named employee with attributes as employee number, employee name, and basic salary. Take input for the details and display them.
#include<iostream> #include<conio.h> using namespace std; class employee { private: int empno; char name[20]; float sal; public: void read(); void show(); }; void employee::read() { cout<<"Enter empno, name and salary "; cin>>empno>>name>>sal; } void employee::show() { cout<<"empno "<<empno<<" name "<<name<<" sal "<<sal<<endl; } int main() { //Normal object employee e1; e1.read(); e1.show(); //pointer type object employee *p=new employee; p->read(); p->show(); return(0); }
Output:
Enter empno, name and salary 1001
Amit
45000
empno 1001 name Amit sal 45000
Enter empno, name and salary 1002
Kapil
56000
empno 1002 name Kapil sal 56000