while the code doesn't compiles?

hi,

I'm taking the C++ course in the university.
The following code was taken from an exam question.
Please help me to understand why the code doesn't compiles?

#include <iostream>
using namespace std;

template <class T>
class A
{
T t;
public:
A(T p) : t(p) {}
const A<T>& operator= (const A<T>& val)
{
t = val.t;
return *this;
}
};

template <class T>
class Son : public A<T>
{
public:
Son (T p):A<T>(p) {}
};

void main()
{
A<int> a(1);
Son<int> b(2);
b = a;
}

I know that the line b = a; is the problem, but can't understand why.
Thanks a lot!
Elad.
Could you please use code tags?

First, main() should return int, not void. Second, look at both of these:

1
2
3
4
5
6
7
8
9
10
// This:
template <class T>
class Son : public A<T>
{
    public:
        Son (T p):A<T>(p) {}
};

// ...and this:
b = a;

What do you notice? You're in uni, so this should be easy.

Edit: Also, A<T>::t is private.

Wazzak
Last edited on
Hi,

Sorry for not using code tagging, this i my first post in this blog.

I know the right why is the main() return int, but it would still work with void.

I found the problem by my self

b is kind of A but a is not kind of Son.

In this case, line 28 is not allowed.
Instead of that a = b; would works fine.

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
#include <iostream>
using namespace std;

template <class T>
class A
{
	T t;
public:
	A(T p) : t(p) {}
	const A<T>& operator= (const A<T>& val)
	{
		t = val.t;
		return *this;
	}
};

template <class T>
class Son : public A<T>
{
public:
	Son (T p):A<T>(p) {}
};

void main()
{
	A<int> a(1);
	Son<int> b(2);
	b = a;
}


Thank you for you're help :)
Topic archived. No new replies allowed.