C++ :: Why Assignment Operator Return By Reference
Feb 1, 2015
I have code here that uses assignment operators that doesn't return by reference and it still works. So why does my book say you need to return by reference?
Here is a quote from my book:
The return type of operator= is a reference to the invoking object, so as to allow chained
assignments a=b=c.
The code below is from my book. I simply removed '&', in the original code that has assignment operators return by reference, from IntCell & operator=. This way the assignment operator no longer returns a reference, and it still works.
#include <iostream>
using namespace std;
class IntCell {
public:
explicit IntCell( int initialValue = 0 )
{ storedValue = new int{ initialValue }; }
[Code] .....
View 3 Replies
ADVERTISEMENT
Mar 6, 2014
Class A
{..........}
Class B:
{....
private U& u;}
I need to write the copy constructor and assignment operator for Class B above. Copy would look something like this:
B::B(conts B& bo): u(bo.u){}
is this correct ... and how will the assignment operation look like??
View 3 Replies
View Related
Apr 7, 2014
I am wondering why return type for an assignment operator cant be a void or int? Cant I write assignment operator for student class like this as we do nothing with returned value?
Student {
char name[20];
int marks;
public:
student(char*name,int marks)
[code].....
View 2 Replies
View Related
Jan 9, 2015
The task is to use the assignment operator of a class, but change all the data except certain ones. For example, below we are to assign all Person data of 'other' except for 'name' and 'ID':
#include <iostream>
#include <string>
struct Person {
std::string name;
int ID, age, height, weight;
[Code] .....
Name = Bob
ID = 2047
Age = 38
Height = 183
Weight = 170
Name = Frank
ID = 5025
Age = 25
Height = 190
Weight = 205
Bob pretends to be Frank, but keeps his name and ID.
Name = Bob
ID = 2047
Age = 25
Height = 190
Weight = 205
But I think the way I did it is pretty lousy (note the wasted steps changing the name and ID only to revert them back? So the ideal solution should require no wasted steps, unlike the method above, and changes to what the exclusions should be should be in only one place (not two like above). Of course, we assume that Person shall have many, many data members (and constantly increasing), so that simply defining Person::operator= (const Person& other) to handle all data except for 'name' and 'ID' is out of the question.
View 3 Replies
View Related
Feb 3, 2014
How do i write main test program to test the copy constructor and assignment operator in this program...how do i know if its working as its suppose to?i just want to know about copy and assignment operator..i have figured out the test program for other things..Here my program :
ListType.h
#ifndef LISTTYPE_H
#define LISTTYPE_H
#include<iostream>
class ListType{
public:
ListType(size_t=10);
ListType(const ListType&);
[Code] ......
View 1 Replies
View Related
May 20, 2013
I've been working on some project and I got to wondering when you know you need to use a copy constructor and an assignment operator. Is there a rule of thumb? I know there is the Rule of Three, but is there something that tells you when you need those three?
View 4 Replies
View Related
Apr 11, 2014
Below is exception proof approach of assignment operator shared by scott meyer. Is it safe to delete the raw pointer.
int *orig =m_p;
m_p=new int (*obj.m_p);
delete orig;
View 1 Replies
View Related
Sep 13, 2013
Go to this link : [URL] .....
Actually I am not getting one thing in this code that why they only provide the declaration of Copy constructor and Assignment operator...??
View 1 Replies
View Related
Nov 12, 2014
how the operator overloaded methods called in C++?
Class String {
int len;
char *str;
public:
String(const char *str1="") {
len=strlen(str1);
str=new char[len+1];
strncpy(str,str1,len+1);
[code]....
View 1 Replies
View Related
May 23, 2013
I designed a class template to create unique arrays. I was able to successfully input data to and output data from my array objects, irrespective of the datatype. However, I can't for the life of me fathom why my overloaded assignment operator worked perfectly well only for integer datatype and not for double/string datatypes.
Here is the class definition:
template <class dataType>
class myArray {
public:
void setArrayData();
[code]....
And here is the definition of the overloaded assignment operator:
template<class dataType>
const myArray<dataType>& myArray<dataType>::operator=(const myArray<dataType>& rightArray) {
int i;
if(this != &rightArray) {
delete [] arrayPtr;
[Code] ....
And here is my main function that tests the operations on objects of the class:
int main(){
//object declarations
myArray<double> list(5); //a single-parameter object declaration of class myArray
myArray<double> myList(2,13); //a two-parameter object declaration of class myArray
[code]....
The problem I'm having starts from where the assignment operator is being tested: for double and string datatypes, the upper input/output section works fine, but the assignment section freezes the display until the program execution is manually terminated!
View 19 Replies
View Related
Jul 27, 2012
/*using GENERIC_COMMAND* A; as volatile generates error. but here i have to use union object as volatile i.e. volatile GENERIC_COMMAND* A; */
#include <iostream>
using namespace std;
typedef unsigned int uint32_t;
typedef unsigned long long uint64_t;
union GENERIC_COMMAND {
[Code] .....
View 14 Replies
View Related
Mar 30, 2013
i am trying to create the assignment operator for a class that uses a pointer for it's private variable. The error is saying expected constructor, deconstructor, or type conversion before "operator. (which is the assignment operator. I have tried everything i could think of or find online and nothing has worked. below is the code for the assignment operator in the .h file and the .cpp file.
//Assignment constructor
indexList &operator=(const indexList <T> &rhs);
template <class T>
indexList<T>::indexList operator=(const indexList <T> &rhs) {
if(this != &rhs) {
numberOfElements = rhs.numberOfElements;
[Code]...
View 1 Replies
View Related
Jan 11, 2015
From the page: [URL] ....
#include <iostream>
using namespace std;
int n;
int& test();
[Code] ....
Explanation
In program above, the return type of function test() is int&. Hence this function returns by reference. The return statement is return n; but unlike return by value. This statement doesn't return value of n, instead it returns variable n itself.
Then the variable n is assigned to the left side of code test() = 5; and value of n is displayed.
I don't quite understand the bold sentence. Shouldn't value of n and variable n be the same?
View 8 Replies
View Related
Aug 28, 2014
Why it is necessary to use the reference operator here ?
const string& content() const {return data;}
Example in [URL] ....
// classes and default constructors
#include <iostream>
#include <string>
using namespace std;
class Example3 {
string data;
[Code] .....
View 2 Replies
View Related
Jun 3, 2014
I dont know what kind of return reference I have to put to override the following derived member function in C++:
virtual SEntityPhysicalizeParams& GetPhysicsParams() override {return ???;}
The place where I should put the return value is marked with ???. SEntityPhysicalizeParams is a struct from another header from which I dont have access to it's source file.
I tried several things but noone seemed to work out and keep getting me either error "function must return a value" or "initial value of reference to non-const must be an lValue".
Here is SEntityPhysicalize where my function is refering to:
struct SEntityPhysicalizeParams
{///////////////////////////////////////////////////////////////////
SEntityPhysicalizeParams() : type(0),density(-1),mass(-1),nSlot(-1),nFlagsOR(0),nFlagsAND(UINT_MAX),
pAttachToEntity(NULL),nAttachToPart(-1),fStiffnessScale(0), bCopyJointVelocities(false),
pParticle(NULL),pBuoyancy(NULL),pPlayerDimensions(NULL),pPlayerDynamics(NULL),
pCar(NULL),pAreaDef(NULL),nLod(0),szPropsOverride(0) {};
[Code] ....
View 8 Replies
View Related
Oct 12, 2014
Okay, so for an assignment I need to write a function called find() that returns a reference to a vector. So I have vector <int> & find(string & key); If I do this, I get the obvious warning warning: reference to local variable 'lineNum' returned [enabled by default].
If I do vector<int> & find(string & key) const; I get a huge error that starts out like
In member function 'std::vector<int>& index_table::find(std::string&) const':
indextable.cpp:74:30: error: no match for 'operator='
Am I using the const identifier incorrectly?
View 5 Replies
View Related
Jun 1, 2014
Suppose i have a function:
int & f1(int & p) {
return p;
}
void main() {
int a,b;
b = 10;
a = f1(b);
a = 11;
cout<<b<<endl;
}
why when i change a, b doesnt change? a is supposed to be an alias of b right?
View 5 Replies
View Related
Jul 26, 2012
Try to implement overloading << operator. If I done it void then everything work fine (see comment out) if I make it class of ostream& then the operator return to me some memory address.
Code:
#ifndef Point_HPP // anti multiply including gates
#define Point_HPP
#include <sstream>
class Point {
private:// declaration of private data members
double x;// X coordinate
double y;// Y coordinate
[Code] .....
View 7 Replies
View Related
May 27, 2013
Say I wanted to overload the modulus operator to return the remainder of a division between two floating point numbers. Why isn't a custom double operator%(double, double) allowed even though that function isn't available in the standard anyway?
View 5 Replies
View Related
Mar 22, 2013
I'm doing a refresher for C++ and have gotten to operator overloading. I'm trying to perform an operator overload with the insertion (<<) operator, but I have encountered a problem.
Here's my class [In a header file "Shinigami.h"]
#include<string>
namespace K{
class Quincy;
class Shinigami{
friend std::ostream& operator<<(std::ostream&, const Shinigami&);
[Code] .....
If the operator function is a friend of the 'Shinigami' class, why doesn't it recognize any of it's private members? I need it to be in this file because I'm doing a bit of association with the 'Quincy' class.
I thought it was the namespace, but I included that.
View 9 Replies
View Related
Mar 29, 2013
I'm writing some functions pertaining to binary trees. I've used recursion once before while learning quicksort but am still quite new and unfamiliar with it. And this is my first time touching a binary tree. So my question: In my addnode function, will the return root statement at the end ever return a value other than the value passed to the function?
Code:
#include <stdlib.h>
struct tnode
{
int data;
struct tnode * left;
struct tnode * right;
}
[code]....
View 4 Replies
View Related
Jun 6, 2013
I am using OpenCV to read and manipulate a set of images, which I need to store in an array to work with them. Here is a snippet of the code:
#define MAX_IMAGES 8
typedef Mat* MatPtr;
int main(int argc, char** argv) {
char imageName[] = "./res/imageX.tiff";
MatPtr datacube[MAX_IMAGES];
[code].....
I have an array of pointers to Mat objects (an OpenCV class used to hold info and data about an image), which I will use to store the images. The function imread reads an image and returns a Mat object loaded with the relevant data about the image.However, this gives me a nice segfault when the assignment takes place. Of course, I can swap it with the following code, but since I'm working with big images (2048x2048 and upwards), it's really inefficient:
for(unsigned int i = 0; i < MAX_IMAGES; i++) {
imageName[11] = 49 + i;
datacube[i] = new Mat(imread(imageName, -1));
}
Is there any way to do this elegantly and without much hassle?Again, excuse my rustiness and anything completely stupid I might have said. It's been a long time since I worked with C++. Managed to circumvent the problem by using a STD vector instead of an array. I'd still like to know the answer to this riddle...
View 6 Replies
View Related
Jun 12, 2013
I pretty much got the assignment done. All it asked for was that you make a C program that displays which manufacturer owned a disk drive based on the code entered. Pretty simple. Just enter 1, 2, 3, or 4 and get the associated manufacturer. Though I am trying to implement an error messege to it for any interger that isn't 1-4.
Code: #include <stdio.h>
int main()
{
[Code]...
o errors are given and it works fine as long as you enter 1-4, but when you enter any other didgit it just stops the program without any messeges.
View 5 Replies
View Related
Oct 11, 2013
I am working on a double linked list and inside of my function to insert a node, I am getting an error of "Incompatible types in assignment". Here is my function code. Line 55 is where I am receiving the error.
Code:
45 struct lnode *ins_llist(char data[], struct llist *ll){
46 struct lnode *p, *q;
47
48 q = malloc(sizeof(struct lnode));
49 if ( q == NULL )
[Code]....
View 2 Replies
View Related
Jul 27, 2013
when i compile the following program i get a compiler warning, but i don't understand why. for me the code seems to be all right and does legitimate this warning. so here is the code
// multiplication.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "crypto.h"
#define PROGNAME "multiplication"
void usage();
int isnumaber(char* str);
[code]....
View 2 Replies
View Related
May 15, 2013
I have a class with member functions and a pointer like this:
Code:
class MyClass{
private:
typedef void(MyClass::*memFnPtr_t) ();
public:
memFnPtr_t fnptr;
void fn1();
void fn2();
};
Now in a regular function I create an instance of the class and try to assign the pointer:
Code:
MyClass mc;
mc.fnptr = &mc.fn1;
The compiler does not like it and suggests this instead:
Code:
mc.fnptr = &MyClass::fn1;
This seems to work but what if I have two instances of the class:
Code:
MyClass mc1, mc2;
How does the compiler know to distinguish between
Code:
mc1.fn1
and
Code:
mc2.fn1
when the assignment now looks identical:
Code:
mc1.fnptr = &MyClass::fn1;
mc2.fnptr = &MyClass::fn1;
View 14 Replies
View Related