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

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

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

Disclosure: My content contains affiliate links.

43,700 questions

57,013 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 346 views
1 answer 288 views
1 answer 243 views
243 views asked Mar 26, 2018 by avibootz
...