What is wrong here ?

What is wrong with this ?
If all things are public why doesn't it work ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include <iostream>
using namespace std;

class Base{
	public: 
	int x,y;
	public:
		Base(int i,int j){ x=i; y=j;}
};

class Derived:public Base
{
	public:
	Derived(int i, int j) { x=i; y=j;	}
	void display() { cout<<x<<" "<<y<<endl;	}
};

int main(void)
{
	Derived q(10,10);
	q.display();
	return 0;
	
}


Here are the errors (it's a screen capture):
https://ibb.co/gcc8Lc
You didn't specify which Base constructor that you want to use when constructing Derived object so the compiler assumes you want to use the default constructor (the one that takes no arguments) but there is no such constructor so that is why you get an error.

Instead of assigning to x and y inside the body of the Derived constructor you probably want to pass them as arguments to the Base class constructor, like this:

 
Derived(int i, int j) : Base(i, j) { x=i; y=j; }
If you want Derived to have all the constructors that Base has you can inherit the constructors using a using-declaration.

1
2
Derived(int i, int j) : Base(i, j) {}
using Base::Base;
Last edited on
Topic archived. No new replies allowed.