regarding new and classes



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  class A{
A();
~A();
virtual void printstuff(){cout << "A::printstuff" << endl;
....... };

class B: public A{
B();
~B();
void printstuff(){cout << "B::printstuff"<< endl;
......};

int main() {
......
A* b2 = new B();
b2->printstuff();

}


What does A* b2 = new B() actually mean? I would guess it means create an object of attribute A which points to B? Why is it also that it prints out A::printstuff of class A? I understand a little of polymorphism but I just do not get how A* b2 = new B(); relates to that. Can anyone explain that certain line of code?
Last edited on
Line 15: This means create an object of type B and assign it to the base class pointer b2 which is type A*.

You have a number of errors in your snippet.
Line 2,3,8,9: These functions do not have bodies.

Lines 2,3,4,8,9,10: These function must be public.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;

class A
{   
public:
    A() {};
    ~A() {};      
    virtual void printstuff()
    {   cout << "A::printstuff" << endl;
    }
};

class B: public A
{   
public:
    B() {};
    ~B() {};  
    void printstuff()
    {   cout << "B::printstuff"<< endl;
    };
};

int main() 
{   A* b2 = new B();
    b2->printstuff();
    system ("pause");
}
B::printstuff
Press any key to continue . . .
Thanks for the correction I am so so sorry, the format was a bit off so I probably removed some lines without noticing. Just curious is it ok to write constructors just as A(); rather A() {}; ?
You have to supply a body for the constructor somewhere. You can write A(); but then you need a body for the constructor in your .cpp file. By specifying A() {} in your header file, you're specifying the constructor is empty.
The constructor that takes no arguments is the default constructor.
If you don't put it into the class at all, then the compiler will add it for you,
except if the class has some other constructor.

You can still explicitly declare the default constructor and ask the compiler to generate its implementation:
1
2
3
4
class A
{   
public:
    A() = default;

See:
http://en.cppreference.com/w/cpp/language/default_constructor
http://en.cppreference.com/w/cpp/language/rule_of_three
Registered users can post here. Sign in or register to post.