Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,948 questions

51,890 answers

573 users

How to use inheritance and protected member in class with C++

1 Answer

0 votes
#include <iostream>

using std::cout;
using std::endl;

class Base {
protected:
	int i, j;
public:
	void set(int _i, int _j) {
		i = _i;
		j = _j;
	}
	void print() {
		cout << i << " " << j << endl;
	}
};

class Derived1 : public Base {
	int k;
public:
	void set_k() {
		k = i + j;
	}

	void show_k() {
		cout << k << endl;
	}
};

class Derived2 : public Derived1 {
	int l;

public:

	void set_l() {
		l = i - j;
	}
	void show_l() {
		cout << l << endl;

	}
};

int main()
{
	Derived1 o1;
	Derived2 o2;
	
	/*
	o1.print();
	o1.set(4, 6);
	o1.set_k();
	o1.show_k();
	*/
	/*
	o2.print();
	o2.set(5, 2);
	o2.set_k();
	o2.set_l();
	o2.show_k();
	o2.show_l();
	*/

	o1.set(4, 6);
	o1.print(); // 4 6

	o1.set_k();
	o1.show_k(); // 10 // 4 + 6

	o2.set(5, 2);
	o2.print(); // 5 2 

	o2.set_k();
	o2.show_k(); // 7 // 5 + 2

	o2.set_l();  
	o2.show_l(); // 3 // 5 - 2

	return 0;
}


/*
run:

4 6
10
5 2
7
3

*/

 



answered Mar 10, 2018 by avibootz

Related questions

1 answer 225 views
1 answer 175 views
1 answer 149 views
149 views asked Mar 26, 2018 by avibootz
...