How do you put a class object onto the stack

I'd like to override the operator 'new' for a class and at the same time allow myself the ability to create an object on the stack. Can't do it nohow with gcc 4.5.3 and am wondering if it is possible to do it at all. I realize that there is ambiguity in the expression 'classType name()' where 'name()' was to be a reference to the constructor. Is there anyway around this?

The code is:
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
29
30
31
32
33
34
35

# include <cstdlib>
# include <iostream>
# include <iomanip>

using namespace std;


class base {
public:
    base* linkLeft;
    base* linkRight;
    base() { output(); };
    ~base() { }
    void output() {
        cout << "Constructor <" 
             << setw(8) << setfill('0') << hex << linkLeft  << "  "
             << setw(8) << setfill('0') << hex << linkRight << ">"
             << endl;
             if (linkLeft != linkRight) linkLeft = linkRight = NULL;
    } // output
    void * operator new(size_t size) { base* cell = (base*)malloc(sizeof(base));
                                       cell->linkLeft = cell->linkRight = (base*)0xDeadBeef; 
                                       return (void*)cell; }
    void   operator delete(void* ptr) { free(ptr); }
};

int main(int argc, char** argv) {
    base b1();
    b1.output();
//    base* b2 = new base();

    return 0;
}
Not sure I follow, using your override new you allocate heap. Creating your class object without using new, allocates it on the stack. Is your main with base b1(); not working?
You are correct. 'base b1()'; does not work. The error message is "error: request for member ‘output’ in ‘b1’, which is of non-class type ‘base()’" One solution may be to include an argument and see if that works - other forums indicate that the error is due to the compiler thinking the declaration is for a function named 'b1()' returning an object of type 'base'. I'm going to try this now.
Darn, someone else is good. I just tried the code with the constructor 'base(int x)' and the constructor call 'base b1(1)'. It worked.
When using a default constructor with no parameters, it's not required to have the parentheses. If you do use the parentheses, the compiler will interpret it as a function, hence the statement of requesting a member from a non-class type.
First of all, as NGen said, deafault constructors are, as thir name suggests, DEFAULT! That means tehey are implicitly called every time a class object is constructed without any other constructor BY DEFAULT. Second of all, the operator new is used to put objects on the HEAP, not the STACK! The call stack is the default place to put objects on! Better read the tutorial ( http://www.cplusplus.com/doc/tutorial/ )! There they explain both default constructors, and which operators are overloadable, and which are not!
Topic archived. No new replies allowed.