Thursday, 21 September 2017

Class template in C++ to accept and display person details

/*
 Class template which have data members of different types
*/

#include "iostream"
using namespace std;

template <class T1, typename T2>
class Person{
 T1 age;
 T2 name;
 public:
  void getData(){
   cout<<"\nEnter age & name ";
   cin>>age>>name;
  }
 
  void showData(){
   cout<<"\nage: "<<age<<"\tname: "<<name<<endl;
  }
};
 
 int main(){
 Person <int,string>ob; // object instantiating with int, string
 ob.getData();
 ob.showData();
 Person <int, char[5]>ob2; // object instantiating with int, char[5]
 ob2.getData();
 ob2.showData();
 return 0;
}

/*
 OUTPUT

[pavan@Pavan ClassTemp]$ g++ ClassTemp1.cpp
[pavan@Pavan ClassTemp]$ ./a.out 

Enter age & name 32 Pavan

age: 32 name: Pavan

Enter age & name 30 Ajay

age: 30 name: Ajay
[pavan@Pavan ClassTemp]$ 
*/

No comments: