LearnFrenzy
Sign in Take a free test

OOPS Concepts · Find the Error · Question 10

Error: initializing a derived object from a base object Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

main.cpp
#include <iostream>
#include <string>

struct Person { std::string name = "Asha"; };
struct Employee : Person { int salary = 50000; };

int main() {
    Person p;
    Employee e = p;
    std::cout << e.salary << '\n';
    return 0;
}
  • A salary must be private
  • B A Person is not an Employee: there is no conversion from base to derived (the salary part would be missing); the reverse direction is allowed Correct
  • C Employee must inherit privately
  • D Strings cannot be members
Correct Answer: Option B

Derived-to-base works (an Employee is a Person, possibly slicing); base-to-derived needs an explicit constructor that supplies the missing parts.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links