self object


Can a C++ class have an object of self type?
Depends on what is meant by "have an object".

closed account (zb0S216C)
Maybe the "this" pointer? Your question is a little broad, don't you think?

Wazza
well i dont.
i mean a class object as an instance of the same class.
No. An object type may not be recursive.

You can have a pointer or a reference to another instance of the container class.

What exactly are you trying to do? Perhaps we can suggest a good way to do it.
#include<iostream.h>
class Base
{
Base b;
};
int main(void)
{
Base b;
}


is this possible?
It is impossible because at the time when data member b is being declared type Base is not defined yet.
You can only do this:
1
2
3
4
class Base
{
    Base* b;
};


But careful, if you do this, you'll have infinite recursion:
1
2
3
4
5
6
class Base
{
    Base* b;
public:
    Base() : b(new Base() ) {}
};



Duoas, I'm not sure how a reference would work. It could compile like this:
1
2
3
4
5
6
class Base
{
    Base& b;
public:
    Base(Base& in) : b(in) {}
};

But you'd never be able to make the first instance of it (unless perhaps it inherits from another class)
Last edited on
inception. it would be like a linked node/list. If it IS allocateable (non virtual)
@Stewbond: Base b(b); compiles just fine (a name introduced by the declarator is visible in the initializer), although its legality is questionable.
@Stewbond: Base(): b(*this) {}
Simulate a null reference via an exemplar.

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <memory>

struct base
{
    base( int d, base& n ) : _data(d), _next(n) {}

    struct null_reference{};

    base& next()
    {
        if( _next.is_null() ) throw null_reference() ;
        return _next ;
    }

    const base& next() const
    {
        if( _next.is_null() ) throw null_reference() ;
        return _next ;
    }

    operator int&()
    {
        if( is_null() ) throw null_reference() ;
        return _data ;
    }

    operator int() const
    {
        if( is_null() ) throw null_reference() ;
        return _data ;
    }

    static base null ; // null reference (exemplar)

    private:
        base() : _data(-99999999), _next(*this) {}

        int _data ;
        base& _next ;
        bool is_null() const { return this == std::addressof(null) ; }
};

base base::null ;

void print( const base& b ) { std::cout << b << " => " ; print( b.next() ) ; }

int main()
{
    base a( 23, base::null ), b( 100, a ), c( 78, b ), d( 245, c ), e( 17, d ) ;

    try { print(e) ; }
    catch( const base::null_reference& ) { std::cout << "null\n" ; }
}


http://liveworkspace.org/code/1jPHFZ$0
Topic archived. No new replies allowed.