C++ :: Can Avoid Class Using Array Operator?

Feb 7, 2014

Imagine these simple class:

Code:
class test {
public:
void write(string a) {
cout << a;
}
};

(these class wasn't tested... it's for these question)... Can avoid the class use the array operator('[]')?

View 7 Replies


ADVERTISEMENT

C++ :: Implementation Of Array Index Operator For Fraction Class

Jan 7, 2014

I need an implementation for the array index operator overloading of my Fraction class . The Fraction.h looks like :

#include <iostream>
using namespace std;
class Fraction {
public:
Fraction(int = 1, int = 1);

[Code] .....

I am not able write the Array index operator overloading functions.

View 3 Replies View Related

C/C++ :: How To Avoid Replacing Element In Array

Oct 6, 2014

I am working on a parking lot scenario project using multidimensional arrays. The parking lot has 8 rows and 10 parking spaces in each row. Altogether there are suppose to be 30 cars parking in the lot and arrive in numerical order. I am suppose to generate a random number to represent the row and another to represent the space in the row.

The problem I have is that a few of the elements are being replaced. The project requires the car to check if the space is taken, if so it is to find another one. Here is what I have...

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 8
#define COL 10
#define CARS 30
void parkTheCars(int result[ROW][COL]);
void displayArray (int result[ROW][COL]);

[Code] .....

View 1 Replies View Related

C++ :: Derived Class Inherit Operator Of Base Class

Jan 17, 2012

If Yes, then why this syntax does not works :

class Derived : public Base {
public:
Derived& operator=(const Derived &rhs) {
operator =(static_cast<const Base&>(rhs));

[Code] ....

View 2 Replies View Related

C++ :: Class Using New Operator

Jan 5, 2015

Is it usual to rely completly on the new operator in constructors/copy constructors. What if new trows an exception? The application ends and that's it? The new operator can be placed where it can't be catch like in constructor initialization list. What kind of practice I should adopt when using "new" in those cases?

The sample code below is taken from here... [URL] ....

class MemoryBlock {
public:

// Simple constructor that initializes the resource.
explicit MemoryBlock(size_t length)
: _length(length)
, _data(new int[length])

[Code] .....

View 9 Replies View Related

C++ :: How To Use The Operator In Class Template In Program

Apr 25, 2013

I have a list of numbers in an array created by a class template

Code:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
const int CAPACITY = 20;
template <class T>
class A

[code].....

View 2 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++ :: Operator Overloading In Inherited Class

Jun 2, 2013

So i am having troubles with operator overloading in inherited class. Basically, it doesnt work. Consider this:

Code:

class A {
public:
A() {
x=0;
z= new int;

[Code] ....

Some how the copy constructor of a is improperly executed - the pointer is copied over, not re-created. As a result, the destructors crashes due to double-free.

*/
B bb = b; //doesnt work
B bbb(b); //doesnt work
B bbbb(b, 0); //works
}

Above code shows the problem well. The "official" copy-constructor wont work - it copies over the pointer directly, and doesnt create a new one as it should. However, if i provide my own pseudo-copy-constructor that works. But ofcourse it's just a cheap work around - and wont actually work in real code (STL).

compiler is VS2008SP1.

View 11 Replies View Related

C++ :: Defining Operator In Abstract Class

Jun 22, 2012

I have an abstract class called Mbase and from it derived two classes: Sparse and Dense. Now I have an array in which its elements can be either Sparse or Dense. So, I delcared the array to have pointers to Mbase class. For example:

PHP Code:
Mbase** A;
Sparse* A1 = new Sparse;
Dense* A2 = new Dense;
A[1] = dynamic_cast<Mbase*>(A1);
A[2] = dynamic_cast<Mbase*>(A2); 

Now, I have operator + defined in Sparse and Dense. but when I do

PHP Code:

A[1]+A[2] 

I get that operator + is not defined for Mbase class. So, I tried to define it in the Mbase class

PHP Code:

class Mbase{
public:
void put()=0;
double get()=0;
Mbase operator +(Mbase A);


However, the last code does not compile complaining that it cannot declare a class of type abstract in Mbase operator +(Mbase A). I think this is because I am returning Mbase instance.

View 10 Replies View Related

C++ :: Overriding Virtual Operator Of Parent Class

Mar 20, 2013

Below is simplified code consists of two classes, namely Parent and Child.

Child is inherited from Parent.

All member functions of class Parent are declared virtual, and they have been overridden in the class Child.

Code 1:

#include <cstdlib>
#include <iostream>
using namespace std;
#define QUANTITY 5
class Parent {

[Code] ....

The output of the code:

Child::showID() -- ID is 1804289383
Child::showID() -- ID is 846930886
Child::showID() -- ID is 1681692777
Child::showID() -- ID is 1714636915
Child::showID() -- ID is 1957747793

Parent::operator=() invoked.

Child::showID() -- ID is 1804289383
Child::showID() -- ID is 846930886
Child::showID() -- ID is 1714636915
Child::showID() -- ID is 1714636915
Child::showID() -- ID is 1957747793

Question:

Why is Parent::operator= invoked instead of Child::operator= ..?

Isn't it already declared virtual and hence would be overridden..?

I need to invoke Child::operator= instead. How to achieve this?

View 12 Replies View Related

C++ :: Operator Overloading In Complex Number Class

May 29, 2013

Write c/c++ code of overloading ^operator in complex number class.

If we have two objects of complex number class as fellows,complex obj3 =obj1 ^obj2 ;

Obj3 reak and imaginary pars will be ,

Obj3.real = (obj1.real)obj2.real
And
obj3.img = (obj1.img)obj2.img

View 1 Replies View Related

C++ :: Two Classes Derived From Same Template Class And Operator

Mar 11, 2013

class A {
// is abstract
};

class B : public A {
// ...
};

[Code] ....
[Code] ....

main3.cpp: In member function ‘FooB& FooB::operator=(const FooC&)’:
main3.cpp:46:44: error: expected ‘(’ before ‘other’
main3.cpp:46:49: error: no matching function for call to ‘Foo<C>::Foo(const FooC&)’
main3.cpp:46:49: note: candidates are:
main3.cpp:19:2: note: Foo<T>::Foo() [with T = C]
main3.cpp:19:2: note: candidate expects 0 arguments, 1 provided
main3.cpp:16:25: note: Foo<C>::Foo(const Foo<C>&)
main3.cpp:16:25: note: no known conversion for argument 1 from ‘const FooC’ to ‘const Foo<C>&’

Is there any way to make it work?

View 1 Replies View Related

C++ :: Creating A Class Called Time - Operator Overloading

Feb 18, 2015

I am creating a class called time and we've had to do operator overloading for <, > , <=, >=, ==, !=, ++, --, >>, <<, * , +, and -.

Well I have done and error checked them all. The only one I cannot seem to get right is the minus and its because of the error checking. I am having issues with times like this

t1 = 0:0:2:3
t2 = 0:0:1:4

t1 - t2 should equal 0:0:0:59 but it returns 0:0:1:-1.
(days:hours:minutes:seconds)

I need it to check for all cases and I just do not know how. Here is the code I have so far:

time operator- (const time& x, const time& y){
time subtract;
subtract.days = x.days - y.days;
subtract.hrs = x.hrs - y.hrs;
subtract.mins = x.mins - y.mins;
subtract.secs = x.secs - y.secs;

[Code] .....

View 1 Replies View Related

C++ :: Error Overloading Operator / Class Template Vector

Feb 7, 2013

I'm trying to implement a vector class in C + +. However when I go to actually run the main, it generates an interrupt operating system.

MAIN.cpp
#include "header.h"
int main() {
// Definisco le istanze delle classi
vettore <int> vet;
vettore <int> vet2;
vettore <int> vet3;

[code].....

View 7 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++ :: Complex Class - Input / Output And Operator Overloading

Jun 30, 2013

I wrote a simple Complex Class and overload input/output and +/- Operators in it!But there is something that doesn't work correctly!I can print an object of that class but I can't print sum of two object or something like that!

Code:
#ifndef COMPLEX_H
#define COMPLEX_H
#include <iostream>
using namespace std;
class Complex {
friend ostream & operator<<(ostream &, const Complex &);

[Code] .....

cout << c3 is Working fine But cout << c1 + c2 is not giving me correct output!

View 3 Replies View Related

C :: How To Avoid Negative Output

Jul 12, 2013

I have a c program that I partially have working. The problem is basically writing a program that allows the user to input the amount of calories they plan to eat a meal and disperse the calories from top to bottom. My program produces the output in the example if I enter 1050 but the issue I noticed if the number of calories is just enough to cover the burgers I get negatives in the other variables.

For example, if I enter a total amount of calories of 1050, I can eat: Output: 2 burgers @ 770 calories (1050 - 770 = 280 calories remain) 1 bag of pretzles @ 170 calories (280 - 170 = 110 calories remain) 1 pear @ 80 calories (110 - 80 = 30 calories remain) 6 tsp. ketchup @ 30 calories If I input 1050 I get the above output but if I input a different integer such as 2000 this is my output 5 burgers @ 1925 calories 0 bag of pretzles @ 0 calories -1 apple @ -80 calories -35 tsp. ketchup @ -175 calories I can't give the full code since this assignment holds a lot of points and was up all night getting it work.

So I'll provide pseudocode

define all 4 variables burger 385, pretzel 170, pear 80, ketchup 5 print out text How many calories can you eat prompt user input
Divide user input into burger How many burgers can bet eaten subtract calories eaten from original user input
Divide calories left into pretzel How many bags can bet eaten subtract burger calories from pretzel calories
Divide calories left after preztel into pear How many pretzels can be eatn subtract pretzels calories from pear calories
Divide calories left over into ketchup how much ketchup can i use show on screen (int total)of burgers @ (int calorie total) calories show on screen (int total)bags of pretzels @ (int calorie total) calories show on screen (int total)pears @ (int calorie total) calories show on screen (int total)teaspoons of ketchup @ (int calorie total) calories

The problem I see is that subtracting the calories from the pear from the left over calories of the pretzel calories leads to a negative. If leftover calories minus 80(pear int) its less then 0 . The calculations from the pear onward to ketchup become incorrect resulting in negative output.

View 6 Replies View Related

C/C++ :: Avoid Using The Goto Function?

Dec 17, 2014

I've been making an RPG in C++ and I've used goto all throughout the program. After receiving an error and Googling how to fix it, I read that you shouldn't use goto. What can I use as a instead of goto, which isn't 'considered bad programming practice'?

View 9 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++ :: How To Avoid Redundant Code In Classes

Sep 4, 2014

ISSUE: How to avoid redundant code in c++ ?

Problem:Say I have a Base class called Car and it has 3 derived classes say Ford, Honda and Audi.

now the issue is all 3 derived classes have exactly same code but minor difference in calling member functions of their r respective engines( these engines have separate class) . example ford class calls code which is exactly same as other 2 classes but do call something like ford_engine-> start() ford_engine->clean() bla bla bla .

//ly honda calls honda_engine->start() honda_engine->clean();

//ly Audi calls audi_engine->start() audi->clean();

now here the issue is it has redundant code in all 3 places with minute difference. Hoow I can have code at one place most probably in Base class and all derive classes uses same code.

View 1 Replies View Related

C++ :: Way / Pattern To Avoid Copying Data

Apr 19, 2013

I have a class buffer, which holds a std::string as member, and a socket_receive function:

struct buffer {
string data;
buffer() {}
buffer(buffer& b) : data(b.data) {}
};
buffer socket_receive() {
buffer tmp;
tmp.data = "1234";
return tmp;
}

so when I write

buffer b = socket_receive();

there is a copy constructor, and the tmp variable is constructed and destructed, is there anyway to improve the performance?

I tried the new c++11 move(), but seems even worse, I must be doing wrong with move(), but I don't know how.

#include <iostream>
#include <string>
#include <ctime>
using namespace std;
struct buffer {
string data;

[Code] .....

View 4 Replies View Related

C# :: How To Avoid Duplicate Updates In SQL Query

Jun 13, 2014

I have table called leavetable where in i have the fields eid, lfrom,lto, reason,status an employee will insert these fields in the leave form except status, status will be updated by admin but there is no unique field in the table so when the admin updates the status as cancel for an id emp001 so whereever this id is present in the table its getting updated to cancel even though it is approved previously.. How to avoid this duplication ?

SqlConnection con = new SqlConnection(Connectionstring);
con.Open();
string sql = "update leavetable set status = '"+status+"' where eid = '"+textBox1.Text+"' and noofdays = '"+textBox5.Text+"'";

[Code] .....

View 7 Replies View Related

Visual C++ :: How To Avoid Memory Fragments

Mar 4, 2015

I am developing a Visual C++ application. There is an object called CMyObject, as follows:

typedef CMap<UINT, UINT, void *, void*> CMyMap;
class CMyObject {
public:
CMyMap *m_pMyMap;
"Some other member variables"
}

Some instances of CMyObject contains a map, some not. Therefore, to save memory, I define a pointer m_pMyMap and create a new CMap object only if the instance contains a map.

When I test my app, with the increase of the CMyObject instance, the number of memory blocks allocated and deallocated is also increasing. There are a lot of fragments during this period. To prevent this, I try to override the new/delete operator for CMyObject and CMyMap. But still find many fragments. So I try to trace into the MFC source codes for CMap. I find CMap is just using an internal buffer to store the hash table(m_pHashTable), as follows:

m_pHashTable = new CAssoc* [nHashSize];

And for each hash entry, it uses:

P = (CPlex *)new BYTE[sizeof(CPlex) + nMax *cbElement];

To allocate the spaces.

I believe these two may be the reason of the memory fragments and want to eliminate them. However, is there a way to override the new/delete operator for codes such as:

new CAssoc* [nHashSize]
and
(CPlex *)new BYTE[sizeof(CPlex) + nMax *cbElement]

So that the spaces will be allocated from my own memory manager instead of from the default heap?

View 1 Replies View Related

C++ :: Bool Operator In Class - Function Call Missing Argument List

Aug 17, 2014

I'm having trouble understanding this error I'm getting in my copy constructor and my bool operator in my class methods file.

error C3867: 'Grid::isLegalMove': function call missing argument list; use '&Grid::isLegalMove' to create a pointer to member

grid.cpp
#include <iostream>
#include "Grid.h"
#include "DUPoint.h"
#include <vector>
#include <sstream>
using namespace std;
Grid::Grid() { }

[Code] .....

View 1 Replies View Related

C++ :: How To Avoid Using Backspace Character With Push Back

Mar 28, 2014

How to avoid using Backspace character with push_back? I'm making a software as an ATM, so when the user try to enter the password the user only sees *******, but when trying to delete it doesn't delete a character. It just adds a new one. Here's my code:

string password2 = "";
cout << "PASSWORD: ";
ch = _getch();
while(ch != 13) //character 13 is enter {
password2.push_back(ch);
cout << '*';
ch = _getch();
}

And also, I try to use pop_back(); but it doesn't work either.

View 6 Replies View Related

C++ :: Threads Giving Error - Call Of Object Of A Class Type Without Appropriate Operator Or Conversion

Jan 27, 2015

I made a simple binary tree then decide to try out threads too. I got the following error:

call of an object of a class type without appropriate operator or conversion

Code:
#include "Tree.h"
#include <iostream>
#include <thread>
void main(void){

[Code] ....

I am having a hard time figuring out why the error exists. I tried adding the new operator but that did not work.

View 11 Replies View Related







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