I'm slightly perplexed. In my int main() I have created two std::unique_ptr, one which points to the parent class "User" and another one that points to the derived class "Admin". I subsequently std::move() these two std::unqiue_ptr to a std::vector of std::unique_ptr. I then pass the std::vector to a stand-alone function which will be able to iterate through the collection. Because I'm coming at this from the base class pointer in the for-loop I am unable to access the AdminFunction(). Why is this? Is there a solution to what I'm trying to achieve without creating an overloaded function? I really hope this makes sense. Sometimes is so hard to explain-code related problems.
// Polymorpism.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <memory>
#include <vector>
class User {
private:
std::string name;
std::string password;
public:
std::string GetName() { return name; }
std::string GetPassword() { return password; }
void BasicUserFunction() { std::cout << "Basic user function\n"; }
};
class Admin : public User {
private:
public:
void AdminFunction() { std::cout << "Admin function\n"; }
};
void DisplayPrivileges(std::vector<std::unique_ptr<User>>&users) {
for (std::unique_ptr<User>&user : users) {
user->BasicUserFunction();
user->AdminFunction();
}
}
int main()
{
std::unique_ptr<User>ptrAdmin = std::make_unique<Admin>();
std::unique_ptr<User>ptrUser = std::make_unique<User>();
std::vector<std::unique_ptr<User>>users;
users.push_back(std::move(ptrAdmin));
users.push_back(std::move(ptrUser));
}
Aucun commentaire:
Enregistrer un commentaire