question

what the problem with this code ? i try to make that template code can inheritance from spcializtion template code but it dose not run

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  #include<iostream>
#include<string>
using namespace std;

template<typename T>
class student:public student{
public:
T num;
student(T n1){num=n1;}
T getnum(){return num;}
void setnum(T n1){num=n1;}
void print1(){
	student::print();
cout<<"the college num is :"<<getnum()<<endl;
}
};

template<>
class student<char>{
public:
	char name;
	student(char n){name=n;}
	char getname(){return name;}
	void setname(char n){name=n;}
	void print(){
	cout<<"the name of student is :"<<getname()<<endl;
	}
};


void main(){
student<int>obj('nou');
obj.print1();

system("pause");
}
sorry i mean this one
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<iostream>
#include<string>
using namespace std;

template<typename T>
class student:public college{
public:
T num;
student(T n1){num=n1;}
T getnum(){return num;}
void setnum(T n1){num=n1;}
void print1(){
	college::print();
cout<<"the college num is :"<<getnum()<<endl;
}
};

class college{
public:
	char name;
	college(char n){name=n;}
	char getname(){return name;}
	void setname(char n){name=n;}
	void print(){
	cout<<"the name of student is :"<<getname()<<endl;
	}
};


void main(){
student<char>obj('nou');
obj.print1();

system("pause");
}



On line 9, you have a parameterized constructor for your student class. Since student inherits from college, it must call the constructor function from the college class.

Because you didn't specify the constructor function to use, the compiler automatically tries to call the default constructor from college. The problem is, you don't have a default constructor. The compiler doesn't automatically create one if there already exists other constructor functions for a class.

So there are a couple ways to fix this: you can create a default constructor for college (probably not want you want) or else you can change the parameterized constructor of student to use the parameterized constructor of college, instead of the (non-existent) default constructor.

To use the parameterized constructor of college:

student(T n1) : college('a') {num=n1;} // passes 'a' to college's constructor

On line 31, you pass 'nou' as the parameter to the constructor of student<char>. The parameter should be of type char, 'nou' is not a valid char.

EDIT: Also you need to define base classes before derived classes.
Last edited on
Topic archived. No new replies allowed.