Question about type matching in C ++?

I read the text in C ++ and get the following code:

class A { };
class B : public A { };

void main() {
   A* p1 = new B; // B may be larger than A :OK [Line 1]
   B* p2 = new A; // B may be larger than A :Not OK [Line 2]
}

I have 2 questions:

  • I do not understand what the author means when commenting on lines 1 and 2
  • Why can't we do in line 2?
+5
source share
8 answers

Well, "more" is not the key. The real problem is the attitude.

Any object class Balso has a type class A( class Balso class Adue to inheritance), so the first line is fine (a pointer to class Amay exactly point to an object class B), but the inversion is incorrect ( class Ait class Bmay not even have a clue about existence class B), so the second line will not compile .

+8

, ++ ( ). ( "" ). , B "isA" A, A B. .

+7

, . . , , downcast.

BTW, main int. void.

+1

, , "" ..
:

class Animal {
  public:
   bool bIsHungry;
};

class Bird : public Animal {
  public:
    bool bIsFlying;
}

,

Animal* animal = new Bird; // B may be larger than A :OK [Line 1]

"bIsHungry" "bIsFlying" . (, "", "bIsHungry", "bIsFlying" "" .)

Bird* parrot = new Animal; // B may be larger than A :Not OK [Line 2]

"bIsHungry". "" ,

if(parrot->bIsFlying)
{   //doSomething()
    ...
}

, " " Animal, "bIsHungry", "bIsFlying" . "" "", .

+1

B A, B * A.

0

B* p2 = new A; , -B , B , A.

:

class B : public A {
public:
    int notInA;
};

B* p2 = new A;
p2->notInA = 5; // Wait, which notInA are we talking about?
                // p2 is really an A, and As don't have notInA!
0

, . , . "" , , , .
B A, B "A" . Sharptooth , "Is-A". "B" - "A" , "A" "B".
, :

string* s = new string("");
int a = 44;
s = (string*)&a; //compiler error if not cast
cout << s; // randomness printed.
0
class B : public A { }; 

A* p1 = new B; // B may be larger than A :OK [Line 1]
B* p2 = new A; // B may be larger than A :Not OK [Line 2]

, , 1 2. 2?

class B class A, - - - , , A, , . B , , , A. -, A , B, , - virtual. , .

, , >= .

A* p1 = new B; // B may be larger than A :OK [Line 1]

- B / , p1. B , A, - - - , B* A*.

B* p2 = new A; // B may be larger than A :Not OK [Line 2]

A, , B . ( ) - . (, p2 = (B *) ( A) ) to treat the memory address in p2 as if it were an B , then it may later try to access additional data it expects to be part of any B which simply doesn't exist in any A`: , ..

0

All Articles