By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,614 Members | 1,620 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,614 IT Pros & Developers. It's quick & easy.

reference to pointer used in ctor (using 'this' in ctor)

P: n/a
template<class T>
class A
{
public:
A() {
T * object = new T(this); //passing instance as parent of nested class
m_obj.push_back(object);
}

~A() {
for (std::vector<T>::iterator it= m_obj.begin();
it != m_obj.end(); it++) delete *it ;
}

private:
std::vector<T*m_objs ;
};

class B
{
public:
friend class A;
~B(){};

private:
B(A* parent):m_parent(parent){}

A* m_parent ;
};
class C
{
public:
friend class A;
~C(){};

private:
B(A*& parent):m_parent(parent){}

A* m_parent ;
};
int main( int argc, char* argv[])
{
A<Bab ; // Ok
A<Cac ; // Croaks here ...
};
Class A instanstiated with B compiles ok, but when instantiated with
class C (that accepts a *&), I get the error message - cannot convert
parameter 1 from A const* to A* - why is that ?

Why is a reference to a ptr being passed as a const ptr ?

If 'this' is a const ptr during construction (I doubt this assertion
very much), then why is it ok to use as a non-const pointer in class B?
Aug 28 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Correction in the sample code I sent:

class C
{
public:
friend class A;
~C(){};

private:
C(A*& parent):m_parent(parent){}

A* m_parent ;
};

BTW, that typo was (OBVIOUSLY), NOT the reason for the error message I
reported getting earlier.
Aug 28 '07 #2

P: n/a
Anonymous wrote:
[..]
class C
{
public:
friend class A;
~C(){};

private:
B(A*& parent):m_parent(parent){}
I am sure you meant

C(A* const& parent) : m_parent(parent) {}
>
A* m_parent ;
};
int main( int argc, char* argv[])
{
A<Bab ; // Ok
A<Cac ; // Croaks here ...
};
Class A instanstiated with B compiles ok, but when instantiated with
class C (that accepts a *&), I get the error message - cannot convert
parameter 1 from A const* to A* - why is that ?

Why is a reference to a ptr being passed as a const ptr ?

If 'this' is a const ptr during construction (I doubt this assertion
very much), then why is it ok to use as a non-const pointer in class
B?
'this' cannot be changed _itself_, that's why you need to put 'const'
right before the '&' in the declaration of the argument.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 28 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.