Thursday, 21 September 2017

Class template having default and parameterized constructors in C++

/*
 Class template having default and parameterized constructors
*/

#include "iostream"
using namespace std;

template <typename T1, class T2>
class Person{
 T1 age;
 T2 name;
 public:
  Person(){
   age = 32; 
   name = "Pavan";
  }
  Person(T1 x, T2 y){
   age = x;
   name = y;
  }
 
  void display(){
   cout<<"\nAge: "<<age<<"\tname: "<<name<<endl;
  }
};
 
 int main(){
 Person <int, string>ob; //instantiating default constructor
 ob.display();
 Person<int, char*> ob2(18, "Raj"); // instantiating patameterized constructor
 ob2.display();
}

/*
 OUTPUT

[pavan@Pavan ClassTemp]$ g++ ClassTemp2.cpp
ClassTemp2.cpp: In function ‘int main()’:
ClassTemp2.cpp:29:34: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
[pavan@Pavan ClassTemp]$ ./a.out 

Age: 32 name: Pavan

Age: 18 name: Raj
[pavan@Pavan ClassTemp]$ 

*/

No comments: