C++ :: Assignment Operator But With Some Member Exceptions

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


ADVERTISEMENT

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 View Related

C++ :: Return Type For Assignment Operator

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

C++ :: Copy Constructor And Assignment Operator?

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

C++ :: Copy Constructor And Assignment Operator

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

C++ :: Exception Proof Assignment Operator

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

C++ :: Assignment Operator For A Class With Reference

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

C++ :: Declaration Of Copy Constructor And Assignment Operator

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

C++ :: Copy Assignment Operator Method Calling?

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

C++ ::  Overloaded Assignment Operator For Class Template Objects?

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

C++ :: Error When Using Volatile Object In Overload Assignment Operator

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

C++ :: Member Function Pointer Assignment?

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

C++ :: Create Assignment Operator For A Class That Uses Pointer For Its Private Variable?

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

C++ :: Extractor Overloading And Member Wise Assignment For Cartesian Class

Apr 6, 2014

I am making a program with a Cartesian class. I want the user to be able to input 2 coordinates, but when I run it it doesn't ask for any values to be entered. It gives this output Please enter the first coordinates: Please enter the second coordinates:

(4.86129e-270, -1.97785e-41)
(4.86143e-270, -1.97785e-41)

Code:
#include <iostream>
#include <istream>
#include <ostream>
using namespace std;

[Code] ....

Also, I want to add a memberwise assignment function to assign the values of coord1 to coord2. How would I go about doing so?

View 7 Replies View Related

C++ :: Why Can't Operator Be Overloaded As A Member Function

Apr 3, 2013

why can't << operator be overloaded as a member function is it because that is the way c++ is written and you just can't or is there another reason because I'm confused.

View 2 Replies View Related

C/C++ :: Value Assignment To Structure Member Inside The Structure?

Oct 7, 2014

Is it possible to assign a value to structure member inside the structure.like.....

struct control{  
char tbi:2 =0;
char res:1 =0;
};

View 6 Replies View Related

C/C++ :: Binary Operator Overloading Using Member Function

Dec 26, 2014

I want to create a program that shows the total of 2 subjects & percentage of student using binary operator overloading with member function in C++.

View 10 Replies View Related

C++ ::  assigning To A Member From Struct Obtained By Overloaded Operator

Jan 27, 2014

I'm trying to assign a value to a member of a struct that I called via an overloaded [] operator. I have the following code for the struct:

typedef struct {
float r, g, b, a;
float operator [](int pos) {
switch (pos) {

[Code] ....

And what I wish to do is

MyStruct a;
a[0] = 0.5;

Is it possible with a struct? How to express this to search engines so I haven't been able to find anything about it. If this is not possible with a struct, is there a way to define something that can do all the following things:

SomeStruct test = {0.5, 0.5, 0.5, 1};
test.g = 1.0;
test[0] = 0.0; // test[0] would be equivalent to calling test.r
float somevalue = test[3]; // test[3] would be equivalent to calling test.a

I hope I've been sufficiently clear.

View 2 Replies View Related

C++ :: Write Prototype Of A Member Function To Overload Insertion Operator

Apr 10, 2014

Consider the class specification below. Write the prototype (i.e. header) of a member function to overload the insertion operator (i.e. <<). The << operator is to output the data members of an instance of class StudentTestScores into an output stream. Your definition should allow for chaining of output operations (e.g. cout << x << y; where x and y are of type StduentTestScires).

#include <string>
using namespace std;
class StudentTestScores{
private:
string studentName;
float *testScores; // used to point to an array of test scores
int numTestScores; // number of test scores

[code]....

View 1 Replies View Related

C++ :: Developing Application Without Exceptions

Feb 27, 2015

Is it possible to develop any application without exceptions? I don't want to try and catch exceptions and remove it.but I want to write codes which should never create exceptions is it possible?

View 3 Replies View Related

C++ :: Exceptions Thrown During Initialization?

Jul 8, 2014

How exactly would one go about throwing an exception from an object's constructor?

Take a look at this snippet:

#include <iostream>
#include <exception>
class ExceptionFoo : public std::exception {
virtual const char* what() const throw() {

[Code].....

View 8 Replies View Related

C++ :: Custom Exceptions With Default Behaviour

May 24, 2013

I've been pondering which of these 2 approaches would make for the best interface for a library: Defining custom exceptions with specific names for different error scenarios but with standard behaviour, or simply using the predefined exceptions from the STL.

This is my current approach:
Code:
namespace rpp
{
class ConnectionError : public std::exception
{
public:
ConnectionError(const std::string &p_err);

[Code] .....

This seems to make for more descriptive code but it adds no functionality and the implementations are completely identical, which seems "off" to me, somehow.

View 8 Replies View Related

C++ :: Catching Exceptions From Initializer List

Jan 4, 2015

In order to test catching exceptions from an initializer list, I deliberately did bad practice by hard coding an argument to a ctor that would cause a std::bad_allocto be thrown. Obviously better practice is to send a variable, but that would cause a compile error, so I hard coded a value.

The program I wrote creates Prime Numbers up to a specified limit which is an argument to the ctor of type std::size_t. The program works fine IMO, using g++ in cygwin:

$ time ./PrimesExe
Limit is 2000000
148933 Primes Created

real 0m1.210s
user 0m1.123s
sys 0m0.046s

Now when I send something invalid like a negative number or something too big for std::size_t, the program seems to run indefinitely, when compiled with g++ under cygwin. I haven't tested it yet on Linux.

However, if I do the same on VS2013 express, it takes about 15 seconds to print the expected caught exception message. I was not expecting it to take so ridiculously long compared to the reasonable amount of work involved in doing primes up to 2 million.

I have read up about what is involved in catching exceptions: stack unwinding, keeping track of what needs to be destroyed etc. But this is 1 object with 1 ctor argument, no Base classes or any other complications. So why such a long or indefinite amount of time?

This whole example is probably contrived, and I am wondering whether exceptions is the right tool for this - it is similar to the divide by zero problem, or could be considered a programming error to call a ctor with a bad argument?

Also, catching an exception thrown by an initalizer list seems a bit awkward in that one seems to have enclose the creation of the object and all subsequent uses of it (and any code in between ) in the same try block, otherwise it goes out scope. I suppose I could try to write a wrapper function that returns a smart pointer reference to a valid object, but I would have to test the validity of it's return too. That's the awkward part - there is probably a better way?

Are there any recommended ways of recovering from initializer list exception, that is, to allow the user to enter a new hopefully valid value and try to create the object again?

View 2 Replies View Related

C++ :: How To Handle The Exceptions Not Caught By Try / Catch

Nov 2, 2014

Here is an example,

Code:

int main()
{
try{
int y = 0;
int x = 2/y;
}
catch(...)
{
cout<<"catch it"<<endl;
}
return 0;
}

If you try, you will find out that catch(...) couldn't catch exception divided by zero. How'd we catch such exceptions?

View 4 Replies View Related

Visual C++ :: Getting Exceptions On Windows 7 And 8 On Different Parts Of Code?

Feb 25, 2015

I'm Getting exceptions on Windows 7 and Windows 8 on different parts of the Code? Why this can be happening, why the difference in behavior?

View 6 Replies View Related

C++ :: Namespaces / Classes - Perform Operator Overload With Insertion Operator

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







Copyrights 2005-15 www.BigResource.com, All rights reserved