Here is my code. I don't understand why I don't reach with b->x
;
main.cpp
#include <iostream>
#include "Nesne.h"
using namespace std;
int main()
{
Derived obj;
Base *b=&obj;
b->a=2;
b->x=3;
return 0;
}
Nesne.h
#ifndef NESNE_H
#define NESNE_H
class Base
{
public:
int a;
Base();
virtual ~Base();
protected:
private:
};
class Derived : public Base
{
public:
int x;
Derived(){};
};
#endif // NESNE_H
Inheritance goes in the other direction.
A pointer to a Derived object can see Base members, but a pointer to Base cannot see Derived members. There is no virtual
for data members, and even for functions it would be virtual only if declared so in Base. (virtual lets you access a Derived version of a function through a Base pointer or reference).
Since the member you want is there, even though it can't be accessed that way, you could use static_cast
to access it:
static_cast<Derived*>(b)->x = 3;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.