I starts to learn the Multiple Inheritance in C++ and I want to print out the addresses of the class components from the header file.
The original header file defines several classes:
#include <iostream>
#include <iomanip>
class Account
{
public:
Account() {}
unsigned long A1;
};
class Employee : public Account
{
public:
Employee() {}
unsigned long E1;
};
class Student : public Account
{
public:
Student() {}
unsigned long S1;
};
class Work_Study : public Employee, public Student
{
public:
Work_Study() {}
unsigned long W1;
};
The cpp file is below:
Work_Study Obj_WS; // declare a Work_Study object;
Work_Study * Obj_WS_ptr = &Obj_WS;
int main() {
std::cout << "Employee Account" << &((Account *) Obj_WS_ptr->A1) << std::endl;
std::cout << "Employee" << &((Employee *) Obj_WS_ptr->E1) << std::endl;
std::cout << "Student Account" << &((Account *) Obj_WS_ptr->A1) << std::endl;
std::cout << "Student" << &((Student *) Obj_WS_ptr->S1) << std::endl;
std::cout << "Work_Study" << &(Obj_WS_ptr->W1) << std::endl;
return 0;
}
There are currently two errors:
The first one is about the ambiguous request for these components.
Test_MI.cpp:12:51: error: request for member ‘A1’ is ambiguous
And with the following note:
note: candidates are: long unsigned int Account::A1 unsigned long A1;
Should I declare the class again in cpp file? Or is there other way?
The other is: lvalue required as unary '&' operand. What does this error means as the components are long unsigned int?
In this multiple inheritance, there are two Accounts for Employee and Student, so if we want to access the Account for Student, we need to cast the pointer to access it because the memory layout is left hand side first with accessing Employee object firstly.