Derived class object in base class member function

Hello :)
I learn C++ from a book,and now I learn about inheritance.
I read this in the book(I try to translate correct):

"Another source of problems is that many function of the "ABC" class are returning or taking as argument a "ABC" object,not a "DEF" object."
DEF is derived class of ABC class.

This seem to be logical,but I tried to test that in a program:
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
#include <iostream>

class base{
public:
	base sub(const base&);
};

class deriv : public base{};


base base::sub(const base& obj){
	std::cout<<"heiho"<<std::endl;
	return obj;
}


int main(){

	base bobj;
	deriv dobj;

	dobj.sub(dobj);
	//dobj=dobj.sub(dobj);

	std::cin.sync();
	std::cin.ignore();
	return 0;
}


Line 22 and 23: I can't understand why line 22 is correct.The function "sub" takes as argument a "base" object , not a "deriv" , though it's working. And I have no constructor in the "deriv" class that takes a "base" object or vice versa.
But line 23 isn't working.
It seems that the compiler can convert a "deriv" object in a "base" object,but vice versa not. Is this true ?
Thanks in advance.
Have a sunny day !
The compiler considers types statically. There is no the copy assignment operator in class deriv that could assign an object of type base to an object of type deriv. So the compiler issues an error for statement

dobj=dobj.sub(dobj);

This statement is equivalent to

dobj = base();

or that it would be more clear

base bobj;
derive dobj = bobj;

However you can call function sub itself because any derived object is at the same time a base object because the inheritance is public.

If you would declare the corresponding copy assignment operator in deriv then the code would be compiled

1
2
3
4
5
6
7
class deriv : public base
{
   deriv & operator =( const base & )
   {
      return ( *this );
   }
};






Last edited on
Thanks :)
So : If I want to use base and deriv class objects the same, I just need a constructor for deriv that takes a base ? ( deriv(const base&)).
Am I right ?

Again a problem,I want to write the constructor in deriv that takes a base:
1
2
3
4
5
6
7
8
9
10
11
12
class base {

protected:
	int bint;
public:
	base(int nbint) : bint(nbint){}
};


class deriv : public base {
	deriv(const base& src) : base(src.bint){}
};

There is a compiler error at line 11:" error C2248: 'base::bint' : cannot access protected member declared in class 'base'"
Where is the problem ? How can I initialize the bint data member in deriv's constructor ?
Sorry for being so annoiyng...
class deriv : public base {
deriv(const base& src) : base( src ){}
Topic archived. No new replies allowed.