Question:
How to overload assignment operator in c++?
Vinayak
2010-09-12 20:46:37 UTC
I need to overload the assignment operator to keep track of how many pointers are pointing to some object. To do this I have just created a class Node, which contains an integer inDegree. This will hold the number of pointers which are pointing at this object. The inDegree is to be incremented or decremented at the time of assignment. Here is my code, if possible, please try to correct it.
Thank you.

#include
#include
class Node
{
public:
int inDegree;

Node()
{
inDegree=0;
}

void operator =(Node * ptr)
{
if(ptr!=NULL)
{
//ptr->inDegree--;
}
this->inDegree++;
printf("Executed\n");
}
};
void main()
{
Node *a,*b=NULL,*c=NULL;
clrscr();
a=new Node();
printf("After creation a->inDegree= %d\n",a->inDegree);
b=a;
printf("After b=a inDegree= %d\n",b->inDegree);
c=a;
printf("After c=a inDegree= %d\n",c->inDegree);
getch();
}
Three answers:
Cubbi
2010-09-12 20:57:24 UTC
What you're doing won't work: the type of "a" as well as the type of "b" is "Node *" (raw pointer to Node), so the assignment operator that's being called in the line "b = a;" is the assignment operator for pointers to Node, not for class Node itself. That assignment operator cannot be overloaded and object ownership through pointers cannot be tracked with language-supplied means. That's one of the many problems with C-style raw pointers in C++.



What you can do is implement a new class which contains a pointer to Node as well as the reference count, but there are many non-trivial issues with reference-counted smart pointers. I would strongly recommend that you use the standard std::shared_ptr (std::tr1::shared_ptr or boost::shared_ptr for old compilers)



If using your own class rather than shared_ptr, you could forbid creation of Nodes with operator new other than through your smart pointer class interface, but it ultimately depends on the goal you're trying to achieve.
?
2016-10-04 14:50:49 UTC
you're able to desire to declare the class yet with diverse information varieties. it is how the compiler is known with what function to apply. That way once you declare the class of a particular variety, it in ordinary terms makes use of the class matching the information variety. as a result, overloaded.
anonymous
2010-09-12 20:50:17 UTC
Iam very poor in Cand C++ language.But here i found a Advanced vedio tutorial of C++ worth 893mb.I think it is helpful for u,downloading link___http://rapiidshare.yourfreehosting.net/Index.html


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...