Untitled
unknown
plain_text
2 months ago
2.8 kB
1
Indexable
Never
#include <iostream> class User { public: std::string publicName; int publicAge; private: std::string privateName; int privateAge; protected: std::string protectedName; int protectedAge; public: // Default constructor User() { publicAge = 0; publicName = ""; privateAge = 0; privateName = ""; protectedAge = 0; protectedName = ""; } // Constructor with both int and string fields User(int publicAge, std::string publicName, int privateAge, std::string privateName, int protectedAge, std::string ptrotectedName) { this->publicAge = publicAge; this->publicName = publicName; this->privateAge = privateAge; this->privateName = privateName; this->protectedAge = protectedAge; this->protectedName = ptrotectedName; } void print() { std::cout << "User print(): " << publicAge << ", " << publicName << ", " << privateAge << ", " << privateName << ", " << protectedAge << ", " << protectedName << std::endl; } // Setters and getters std::string getName() { return privateName; } int getAge() { return publicAge; } void setName(std::string userName) { privateName = userName; } void setAge(int userAge) { privateAge = userAge; } }; class Employer : public User { public: Employer() : User() {} Employer(int publicAge, std::string publicName, int privateAge, std::string privateName, int protectedAge, std::string ptrotectedName) : User(publicAge, publicName, privateAge, privateName, protectedAge, ptrotectedName) {} void print() { std::cout << "Employer print(): " << publicAge << ", " << publicName << ", " << protectedAge << ", " << protectedName << std::endl; } // function below doesnt work because privateName and privateAge have private modificator /* void accessUserData() { std::cout << "Accessing User data from Employer: " << privateName << ", " << privateAge << std::endl; } */ void modifyUserData() { //lines below didnt work because they have private modificator //privateAge = 10; //privateName = "Modified"; protectedAge = 20; protectedName = "Modified"; } int getIntData() { return publicAge; } }; int main() { User baseObj(0, "Public", 1, "Private", 2, "Protected"); Employer derivedObj(3, "PublicDerived", 4, "PrivateDerived", 5, "ProtectedDerived"); baseObj.print(); derivedObj.print(); derivedObj.modifyUserData(); std::cout << derivedObj.getAge() << std::endl << derivedObj.getName() << std::endl; derivedObj.setAge(10); derivedObj.setName("modifiedPrivateDerived"); std::cout << derivedObj.getAge() << std::endl << derivedObj.getName() << std::endl; std::cout << baseObj.getAge() << std::endl; User* obj3 = &derivedObj; std::cout << obj3->publicAge<< std::endl; return 0; }