Sunday, May 10, 2009

What is the need of copy constructors & assignment operator overloading in C++?

copy constructors are cloning an abject. assignmet operator is there to enable saying a = b for objects, especially those with pointer members. if you don't define them, the compiler will define them for you, but very dangerous to use compiler defined ones if your object has pointers. Because then you would have two objects sharing member data. if you delete this data using this, and rfer to it through the other object, your code crashes.. hope this helps

What is the need of copy constructors %26amp; assignment operator overloading in C++?
C++ supports 'poly-morphism'. This means that functions and operators can perform more than one task depending on the type of data. When a function or an operator exists in mopre than one form, it is said to be overloaded. Suppose you have declared a class complex which represents complex objects, then performing a taks like assigning one complex object to another would need code like assign(comp1, comp2); however, overloading allows you to write code like comp2 = comp1 by overloading operator =. Note that is no longer an opertor. It is now a function and will perform the task as defined by you. So if you write code that will add the two complex objects in the definition for =, comp2 = comp1 will result in addition instead of assignment.
Reply:These are needed to change the default behavior of what happens when an instance is copied to another instance. By default, each member of the class or struct are copied one by one from one instance to another. For instance, assume you have two instances of class Person called p1 and p2. The class has two fiels, FirstName and LastName. When you say:


p1 = p2;


then the FirstName and LastName fields from p2 are copied to p1.


That's the default behavior.





Now, if you want to change that default behavior, then you specify a custom copy constructor and an assignment operator for the class Person to do something other than member-wise copy.





You need *both* the copy constructor and assignment operator.


The copy constructor is invoked when the copy is made at the time that the new instance is constructed, as in:





Person p2 = p1;





The assignment operator is invoked if the copy is done after p2 is already constructed, as in:





p2 = p1;





Hope this helps.


I wanna to know about operator overloading in c++.?

please suggest standard books on OOP

I wanna to know about operator overloading in c++.?
Try reading the book Deitel %26amp; Deitel C++ how to program.


If you dont have it. Go to www.deitel.com


You can download powerpoint slides from there, as an easier solution.
Reply:hey how to explain ya operator overloadin here thru just a small thing,may b we can chat-generoushous@yahoo.com .ok well operator overloadin is a feature where u can make operations on the user defined data dypes,like u can not add two objects,but using u can do the same thing,but u can not overlaod things like :?,::,.* ..its a vast topic u can evn convert data types,,so well about the book,u can consult robert lafore,ur an indian so u can chk out balagurusami,n for higher concepts stroutsoup n lipmann is there for ya..happy studin'...
Reply:"Thinking in C++" by Bruce Eckel, free download @ www.bruceeckel.com

flower show

What is meant by Operator Overloading in C++?

I need a detailed explanation in easy words. Please help me !!!!

What is meant by Operator Overloading in C++?
Operator Overloading provides the ability to use the same operator to perform different actions


In C++ the satament


c = a + b


will compile successfully if a, b and c are of int and float types


And if we attempt to compile the statement when a,b and c are the objects of user-defined classes,the compiler will generate error message but with operator overloading, this can happen.


Take an example


#include%26lt;iostream.h%26gt;


class student


{


int roll_numb;


int age;


public :


student(int rn,int ag) //constructor definition


{


roll_numb = rn


age = ag


}


void operator ++() //overloading unary operator


{


age = age + 1;


}


}


void main()


{


student ram(1200,19)


++ram; //this will increase the age of ram to 20)


}


This is the example of unary operator where only one operand is required








Now the example binary operator overloading where two operands are required


#include%26lt;iostream.h%26gt;


class student


{


int roll_numb;


int age;


public :


student(int rn,int ag) //constructor definition


{


roll_numb = rn;


age = ag;


}


student operator +(student obj)


{


student temp(0,0); //roll_numb and age initialized to 0


temp.age = age + obj.age;


return temp;


}


};


void main()


{


student ram(1200,19) , mohan(1201,20);


student ramesh(0,0);


ramesh = ram + mohan; //add the age of ram and mohan


and assign the sum to the


age of ramesh


}





student operator +(student obj)-%26gt;


this operator function has student class return type and has one


student class type argument


calling of this function-%26gt;


ramesh = ram + mohan


ramesh - student class type return type


ram - the object which called the function


mohan - the student class type argument
Reply:Operator overloading just means the same thing as overloading any other thing in C++. Overloading in C++ means you are replacing something with another function which might be similar but does things a little different. In other words operator overloading is just like function overloading just applied to an operator. You can basically write a function in C++ that will overload the ++ operator and instead will do a subtraction operation. The compiler will know to use your overloaded function rather then the original function usually based on the type of variable you pass to the function or the type it returns. I would have put in some code samples but yahoo doesn't really like it when i do that.
Reply:Operator overloading means, an operator which is doing more than one jobs.


for ex: %26gt;%26gt; symbol is for getting value from keyboard (like cin %26gt;%26gt; a;)


%26gt;%26gt; symbol is also used for right shift .so this is an operator overloading.
Reply:your computer processor is not compatible with the c++ programming language you have to use another programming language
Reply:A symbol like '+' '-' '/' is called an 'operator' because is signifies an operation (+ for addition). However, the actual operation depends on the data type of the operands (5+6 makes sense but a+b does not, if the operation is additon). Operator overloading refers to the tchnique where in the same operator signifies different operation depending upon the data type. For example '+' can mean addition or concatenation according as the operands are numbers or characters. So a program using operator over loading on the '+' symbol would result in 11 if the operands are 5 %26amp; 6 and 'ab' if they are 'a' %26amp; 'b'. It would use the same line of code to give different results depending upon the operand type. Since the same operator is being used to signify two different operations, the operator is loaded with more than one operation hence the term operator overloading.
Reply:Best and easy expaination along with examples available at:
Reply:hang on ill look for ya, no thats not it, is there any codes with it?


Help stream operator overloading in c++?

actuall i want to ask why do we call by refrence and then return it in the following . i mean the changes must hav been reflected.





ostream%26amp; operator %26lt;%26lt;(ostream %26amp;os,const Base %26amp;obj)


{


os%26lt;%26lt;obj.strVal;


return os;


}

Help stream operator overloading in c++?
At the time of the return, the changes *have* been reflected in the stream "os".





Returning the non-const reference to the stream facilitates chaining of the "%26lt;%26lt;" operator. The most prevalent use of such chaining is when using cout.


Operator overloading in C++?

hi everyone..


can you please tell me how to make overloading for the operater =....


and explain if you can...


thanx

Operator overloading in C++?
1- Since it is one of the assignment operators (=, +=, -=, etc.), it MUST be overloaded as a non-static (public) member function in your class, because it will operate on user-defined objects.


2- Considering the above and the fact that it is a binary operator, the assignment operator (=) will be overloaded with one argument.


3- So a call like a = b for example, will be treated as a.operator=(b), where a and b are objects of your class.


4- The following is an INCOMPLETE example from my book.** It is a user-defined "Array" class.


5- Defining a proper COPY CONSTRUCTOR is essential for using the overloaded assignment operator correctly.


6- Notice the use of the ampersand operator (%26amp;) to indicate "lvalues", and the use of "this" pointer to allow cascaded calls (e.g., a = b = c ).


7- I've enclosed links to download the COMPLETE version of this example. Below you'll find two links, one for the Array.h file and the other for the Array.cpp file. It is really a rich example to learn about operator overloading. Don't worry about copyrights, this example is completely FREE, says the author!





class Array


{


public:


Array ( int = 10 ); //default constructor


Array ( const Array %26amp; ); //copy constructor


const Array %26amp;operator= ( const Array %26amp; ); //overloaded (=)


private:


int size;


int *ptr;


}


--------------------------------------...


// overloaded assignment operator;


// const return avoids: ( a1 = a2 ) = a3


const Array %26amp;Array::operator=( const Array %26amp;right )


{


if ( %26amp;right != this ) // avoid self-assignment


{


// for Arrays of different sizes, deallocate original


// left-side array, then allocate new left-side array


if ( size != right.size )


{


delete [] ptr; // release space


size = right.size; // resize this object


ptr = new int[ size ]; // create space for array copy


} // end inner if





for ( int i = 0; i %26lt; size; i++ )


ptr[ i ] = right.ptr[ i ]; // copy array into object


} // end outer if





return *this; // enables x = y = z, for example


} // end function operator=


--------------------------------------...





Hope that helped!
Reply:try this tutorial: http://publib.boulder.ibm.com/infocenter...
Reply:class someClass


{


public:


...


someClass %26amp; operator=(const someClass %26amp;s);


...


}


C++ and operator overloading?

I CAN'T FIGURE THIS OUT!!





In some applications, it is desirable to produce a concatenated String object without modifying the String arguments. Implement operator+ to allow operations such as





string1 = string2 + string3

C++ and operator overloading?
Use append(). And remember that





a + b





is the same as





operator+(a, b)





So implement a function named operator+ with the following signature:





string%26amp; string::operator+(string%26amp; s1, string%26amp; s2);

phone cards

Few exmples of operator overloading in c++?

i want to know about the syntex of overloding the operators


in c++ these operators are ++,+,=,%26lt;,%26gt;

Few exmples of operator overloading in c++?
check this link out: http://publib.boulder.ibm.com/infocenter...
Reply:there are comprehensive references in the net,just google it


Operator overloading in c?

i want to know if operator overloading is possible in C??

Operator overloading in c?
every once in awhile its good to take a break ...
Reply:yes its possible. The only C operators that can't be overloaded are . and ?: (and sizeof, which is technically an operator).





for example :


http://72.14.235.104/search?q=cache:2QdI...


Operator Overloading in C++?

Explain in Details Operator Overloading in C++ with Web reference.

Operator Overloading in C++?
go through the operator overloading section in stroustoup's C++ book and do yourself an favour by coding few overloading example
Reply:http://www.cs.caltech.edu/courses/cs11/m...
Reply:Operator overloading is under polymorphism a special feature in C++. While the operators in C have usual meaning operator overloading in C++ allows us to overload the operator to give the certain user defined functionality to the operator.





Syntax goes like this


operator x(arguments)


{


functionality


}





where x is an operator





operator overloading is generally used to operate the objects using operators instead of operating their members.


Operator overloading in c++?

How do I overload the [] operator in c++? I have a card deck class where I want to access cards by deck[1], instead of deck.getCard(1).





Note: I have a private vector where I am storing the cards.

Operator overloading in c++?
int operator [] (int ndx)


{


// put anything you want here to accesss


// element "ndx". Just return the value


// of that element as the return value of


// this function.


return value_of_ndx_element_of_your_vector;


}
Reply:Lost me with vectors, but I do a web search for c++ tutorials and most allow you to search their sites for specific answers.

orange

C++ "=" operator overloading?

I have following class, I want to overload “=” operator, I did as following but I cant get success, any one can help me please


class String


{


private:


char * name;


public:


const char * getName() const { }


void setName(const char * aname) { }


friend char * operator=(char %26amp; str, const String %26amp;rhs );


}





char * operator= (char %26amp;str, const String %26amp;rhs )


{


str = const_cast%26lt;char * %26gt;(rhs.getName())


return *str;


}





Void main()


{


String obj;


Obj.setName(“Hello World “);


Char * myString = Obj;


Cout%26lt;%26lt;myString;


}

C++ "=" operator overloading?
Sure.





Your problem here is that the parameters for your operator = are (char %26amp;, String %26amp;). You have two problems here.





First, you want to make that char *%26amp;, not char %26amp;. As defined here, you have an operator = that copies a string into a single character.





The second problem is a little bigger. You are copying a pointer here instead of doing any sort of copying of contents. When done, myString wand Obj will point at the SAME string.





While this makes for a very fast copy, you're almost guaranteed to have problems later:





1. Notice what happens to myString when Obj is deleted. myString is now pointing at deleted memory. The reverse is true as well.





2. If myString changes, so does Obj. The reverse is true as well.





3. There is no safe way to destroy the name * in your string object because you don't know how many copies were made, and if those are still in use. I'm assuming here that the implementation of setName() will allocate new memory for name, and that your full version has a destructor.





I hope this helps. Good luck.
Reply:You have completely mixed your metaphors here.





First off, your operator = only needs to take one parameter, not two -- and that parameter is whatever type you want to be able to assign TO your String.





Second, your operator = should return a String%26amp;.





Third, in order to assign a String object to a char*, you need to overload the char* cast operator.





And finally, make sure you understand that char* is just a pointer -- to actually put anything IN your string, you're going to have to dynamically allocate memory.


C++ operator overloading question?

Why would:


vectorClass nv = vectors[0] + vectors[1];


cout %26lt;%26lt; vectors[0] %26lt;%26lt; " + " %26lt;%26lt; vectors[1] %26lt;%26lt; " = " %26lt;%26lt; nv %26lt;%26lt; endl;





work, While:





cout %26lt;%26lt; vectors[0] %26lt;%26lt; " + " %26lt;%26lt; vectors[1] %26lt;%26lt; " = " %26lt;%26lt; vectors[0] + vectors[1] %26lt;%26lt; endl;





would not.





Here is some implementation:





vectorClass operator + ( const vectorClass %26amp;left, const vectorClass %26amp;right )


{


int a, b, c;


a = left.x + right.x;


b = left.y + right.y;


c = left.z + right.z;





return vectorClass( a, b, c );





}





ostream %26amp; operator %26lt;%26lt; ( ostream %26amp;out, vectorClass %26amp;right )


{





out %26lt;%26lt; "[" %26lt;%26lt; right.x %26lt;%26lt; ", " %26lt;%26lt; right.y %26lt;%26lt; ", " %26lt;%26lt; right.z %26lt;%26lt; "]";





return out;


}

C++ operator overloading question?
add another overloaded function like this


vectorClass operator + (const vectorClass %26amp;right )


{


int a, b, c;


a = x + right.x;


b = y + right.y;


c = z + right.z;





return vectorClass( a, b, c );





}
Reply:Could it be the simple allocation of the class?


Not a ++ major, but even my old school, we had to allocate the memory....which is what vectorClass nv =





does.


C++ operator overloading?

You can overload the common arithmetic operators like +,-,* to perform different operations with the objects of the class.... but is it possible to overload the power or exponential operator '^' as well using the usual operator overloading procedure?

C++ operator overloading?
You can overload ^ but there is one important thing you need to remember. Normally ^ is the bitwise xor operator and it has a lower precedence than the arithmatic operators and you cannot change precedence by overloading. So





a ^ b - c;





is not going to do what you expect unless you use parenthesis, namely





(a ^ b) - c;
Reply:Yes, but you need to override the math library. You can write your own library that calls the math library for the basic and then overload it.