C++ problem???

Status
Not open for further replies.

Crazyguy

Seniorius Lurkius
41
My problem isn't really with C++ but rather with my professor, he recently handed out our latest assignment and no one in my class even knows where to begin... Since i can't find anyone who can help me in the slightest, asking the professor gets me nowheres fast... i thought i'd post the question and see if anyone can help us get started...

Problem:

In order to manipulate complex arrays you need to define two classes,
namely, Complex and CArray. The Complex class shoud have a conversion
constructor to convert one or two doubles to a complex, and a copy
constructor. It should have c_abs(c) friend function to calculate the
absolute value of the Complex c.It should also overload the =, +, -,
*, /, <<, and >> operators. Similarly, it should overload these
operators as well as % (inner product), ^ (cross product), ==, !=,
and [] operators. The CArray class should have copy and conversion constructors: from one or two doubles to Carray; from Complex to CArray.

What the hell does this all mean?

I've started writing both the class's but i'm having trouble overloading operators in class Complex, and also with the conversion constructors of both classes

Any Advice is greatly appreciated. :D
 
A conversion constructor is a constructor that takes an argument (doubles in your case) and intializes an object based on those argument(s). Well, at least that the basic idea. So a conversion contructor is really any contructor that is not the default contructor (which takes no arguments) and not the copy constructor and is not also declared as explicit. If you don't know what the explicit keyword does, don't worry about it. Consider the following:
code:<HR>
Code:
class foo {
  double x, y;
  foo();             // default contructor
  foo( const foo& ); // copy constructor
  foo( int );        // conversion constructors
  foo( float );
  foo( double );
};<P>int main( void ) {
  foo f1;           // use default contructor.
  foo f2(1.0f);     // uses float contructor.<P>  f1 = 3.4;         // foo( double ) constructor to convert 3.4 to type foo.
}

As for operator overloading, it might be better if you could post any specific problems you're having. Myself and other here are happy to help you to understand the syntax and other problems you might run into (like wtf does operator overloading do ;) ), but I'm not interested in doing you're homework for you. Programming is learned by doing.
 

klimas

Ars Scholae Palatinae
632
Operator overloading, hopefully, is intended to make things more readable. If you couldn't overload operators, you'd have to use expressions like this:

(bar.plus(baz.mod(quux.plus(new Frob(32))))).print();

which, apart from having to figure out how many parentheses you need t close when it's all over, isn't half as clear as:

cout << bar + (baz % (quux + 32));

Granted, this is a bit of a contrived example, but things can get like this in Java, which doesn't do overloading. The flip side is that you can get perverse with the overloading and make + raise things to the fourth power or something.
 

Crazyguy

Seniorius Lurkius
41
in overloading the "/" operator i did:
code:<HR>
Code:
Complex Complex::operator / (const Complex &x)
{<P>	Complex t;
    	
    	t.real = (x.real * real + x.imaginary * imaginary) /
    		 ((real * real) + (imaginary * imaginary)) ;
    	t.imaginary = (real * x.imaginary - x.real * imaginary) /
    		 ((real * real) + (imaginary * imaginary)) ; 
    	
    	return t;
}

would the use of the *this pointer be more effiecient and readable???
 
What you have there is technically correct, however as a matter of style overloaded operators that don't modify either operand should be friend functions. And there should be no whitespace between operator and / in your function declaration, operator/ is the correct name. To see why, consider that you can call operator/ like so: this->operator/(foo); however this->operator / (foo); is a syntax error.

Also order of operands is important when overloaing operators. IOW,
friend complex operator/( const complex&, double ) is different from
friend complex operator/( double, const complex&; )

EDIT:
Also, feel free to take a look at the C++ standard library's implementation of the std::complex class for *ahem* inspiration. And, also to check your implementation for correctness, as far as test data goes.
 
I do not think that <span style="font-family: monospace;">operator^</span> has the right precedence to do what you're being asked to make it do properly. It's lower than that of binary <span style="font-family: monospace;">operator+</span> and <span style="font-family: monospace;">operator-</span>, when it should be higher.

What is <span style="font-family: monospace;">operator[]</span> going to be used for? Treating the number as an array of <span style="font-family: monospace;">double</span>?
 

JiveTurkey

Ars Tribunus Angusticlavius
6,299
Subscriptor
<BLOCKQUOTE>code:<HR>
Code:
int main( void ) {
  foo f1;           // use default contructor.
  foo f2(1.0f);     // uses float contructor.<P>  f1 = 3.4;         // foo( double ) constructor to convert 3.4 to type foo.
}
"
<HR></BLOCKQUOTE>
I think
code:<HR>
Code:
int main ( void ) {
   foo *f1;
   f1 = new Foo();
   etc...
At least that was the way I was taught to be most efficiant and over all better coding practice.
 
In general, a container class should know nothing of the implementation of the objects it will store. In this case, the array class simply needs to provide a means for accessing and mutating the elements in the array. This is exactly the reason you can overload operator[]. Your array class should provide an overload of operator[] so the following expression are valid.
code:<HR>
Code:
CArray  ary;
Complex c;<P>ary[0] = c;
c = ary[1];
ary[2] = 2.4; // Note that here a conversion constructor from your
              //  Complex classs will be used for the assignment.

On side note, judging by the requirements of this assignment, your professor seems to have no clue about good C++ class design. Overloading, % and ^ for inner and cross product is absolutely terrible C++ IMHO. And overloading [] for the Complex class is nearly as bad.
 
<span style="font-family: monospace;">operator%</span> at least has the right precedence (being the same as binary <span style="font-family: monospace;">operator*</span> and binary <span style="font-family: monospace;">operator/</span>). Using <span style="font-family: monospace;">operator*</span> for both multiplication by a scalar, and also one product, and <span style="font-family: monospace;">operator%</span> for the other wouldn't be /so/ awful.
 

altie

Ars Scholae Palatinae
795
Originally posted by Crazyguy:
thanks phridge :)


speaking of... what purpose does overloading an operator serve???

my impression is that it allows to add, subtract, etc objects of a class to eachother .... and to allow the input/output such as cin >> var1 >> var2

am i on the right track or out in right field somewhere's?

I'm no professional software engineer, but here's my take on it:

Operator overloading allows for the use of your newly created class as if it was a basic type already implemented in C/C++. For example, suppose you make a class "foo." In the basic interests of object-oriented programming, you want for anyone to be able to use foo without having to know how it works internally. If you create a function prototyped as "foo foo::eek:perator+(int);", then someone can use a foo variable in the method z = x + y, where z and x are foos and y is an int. Then, with function polymorphism (an overly complicated way of saying "defining the same function more than once to accept different types of input" if you're new to the concept), you can make it so that you can add, subtract, multiply, and whatever the hell else you like to foo to your heart's delight.
 
One of the keys to "good" operator overloading is given that the user knows nothing about the internals of your class, the meanings of the operators you overload should be easily inferred from the context they appear in. Which is a fancy way of say if you overload + it should do addition. Your overloads shouldn't stray far from the original meaning's of the operators.

Overloading the modulus and xor operators for the purposes of multiplication is horrific to say the least. Teaching C++ programmers that these kinds of overloads are acceptable C++ style, is even worse.
 

Crazyguy

Seniorius Lurkius
41
here's the code... i can't figure out why its not compiling

code:<HR>
Code:
 // CArray.CPP
#include <iostream.h>
#include <stdlib.h>
#include <assert.h>
#include "CArray.h" // Initialize static data member at file scope<P>
int CArray::arrayCount = 0;   // no objects yet // Default constructor for class Array<P>CArray::CArray(int arraySize)
{
   ++arrayCount;             // count one more object
   size = arraySize;         // default size is 10
   ptr = new Complex[size];      // create space for array of complex numbers
   assert(ptr != 0);  // terminate if memory not allocated    for (int i = 0; i < size; i++)
   {
      
	   ptr[i] = 0;
   
   } 
}<P> void CArray::copy(const CArray &a)
{
size = a.size;
   ptr = new Complex[size];      // create space for array of complex numbers
   assert(ptr != 0);  // terminate if memory not allocated    for (int i = 0; i < size; i++)
   {
      
	   ptr[i] = a.ptr[i];
   
   }
} // Copy constructor for class Array<P> CArray::CArray(const CArray &a)
{
   
	 ++arrayCount;             // count one more object
	 copy(a);<P>} // Destructor for class Array<P> CArray::~CArray()
{
   
	 --arrayCount;             // one fewer objects
     delete [] ptr;            // reclaim space for array<P> } // Get the size of the array<P> int CArray::getSize() const { return size; } // Overloaded assignment operator<P>const CArray &CArray::operator=(const CArray &right)
{
   if (&right != this)      // check for self-assignment
   {
     
		delete [] ptr;        // reclaim space
		copy( right);
   
   }    return *this;   // enables x = y = z;
} // Determine if two arrays are equal<P>bool CArray::operator==(const CArray &right) const
{
   if (size != right.size)
   {
      
	   return false;    // arrays of different sizes
   
   }
   for (int i = 0; i < size; i++)
   {
      if (ptr[i] != right.ptr[i])
      {
         
		  return false; // arrays are not equal
      
	  }
   }
  
   return true;       // arrays are equal
} // Determine if two arrays are not equal and
// return 1 if true, 0 if false.<P>
bool CArray::operator!=(const CArray &right) const
{
   
	return !(*this == right);           <P>} // Overloaded subscript operator<P>
int &CArray::operator[](int subscript)
{
   // check for subscript out of range error
   assert(0 <= subscript && subscript < size);    
   return ptr[subscript];   //  creates lvalue
} <P>const int &CArray::operator[](int subscript) const
{
   // check for subscript out of range error
   assert(0 <= subscript && subscript < size);    
   return ptr[subscript];   //  creates rvalue
} // Return the number of Array objects instantiated<P>
int CArray::getArrayCount() { return arrayCount; } <P>// Overloaded input operator for class Array;
// inputs values for entire array.
istream &operator>>(istream &input, CArray &a)
{
   for (int i = 0; i < a.size; i++)
   {
      input >> a.ptr[i];
   }    return input;   // enables cin >> x >> y;
} // Overloaded output operator for class Array
ostream &operator<<(ostream &output, const Array &a)
{
int i;
   for ( i = 0; i < a.size; i++)
   {
      output << a.ptr[i] << ' ';       if ((i + 1) % 10 == 0)
      {
         output << endl;
      }
   }    if (i % 10 != 0)
   {
      output << endl;
   }    return output;   // enables cout << x << y;
}
 
Why does your overload of operator[] return an int&, it should return a reference to the data type stored in the array. You create an array of Complex objects, therefore operator[] should return a Complex&.

As for syntax errors, I'd need more code to run it through VC++ and see what its complaining about. Or you could post just the lines it flags errors for, along with the error number VC++ gives.
 
assert(ptr != 0); // terminate if memory not allocated for (int i = 0; i < size; i++)
{

ptr = 0;

}
This is pointless. new should throw an exception if it doesn't find memory, not return null (there is a new that returns null, but the call is different). So there is no need to check for null (this goes for all your code). Also, you should provide a default constructor for Complex that initializes it to 0 instead of doing it explicitely in CArray.
In your copy(...) member function, you forgot to delete the current pointer before allocating memory for the new data. Be careful though, doing so will break some of your code.

when i look it up on google it just says that its a deficeny in the compiler.... anyone know of a better compiler i can get for future reference?
Borland's command-line C++ compiler is free and very good at compiling C++. And it's easy to use.
 

Crazyguy

Seniorius Lurkius
41
here's my class defintion of class CArray ... i'm having trouble determining when to return type complex versus type int...

code:<HR>
Code:
 #ifndef CARRAY_H
#define CARRAY_H #include <iostream.h> class CArray<P>{
   friend ostream &operator<<(ostream &output, const CArray &a);
   friend istream &operator>>(istream &input, CArray &a);<P>public:
   CArray(int size = 10);             // default constructor
   CArray(const CArray &a);            // copy constructor
   ~CArray();                         // destructor
   int getSize() const;              // return size
   const CArray &operator=(const CArray &right);  // assign arrays
   bool operator==(const CArray &right) const; // compare equal
   bool operator!=(const CArray &right) const; // compare !equal
   int &operator[](int subscript);             // subscript operator
   const int &operator[](int subscript) const; // subscript operator
   static int getArrayCount();          // Return count of
                                        // arrays instantiated.
private:
   int *ptr; // pointer to first element of array
   int size; // size of the array
   static int arrayCount;  // # of Arrays instantiated
   void copy(const CArray &a);
}; <P>#endif<P>
 
code:<HR>
Code:
 int *ptr; // pointer to first element of array
If you want to store Complex objects, I'd suggest a Complex* ;) This might be the error you're getting, although I doubt it.
VC++ never throws on new failure.
Well that's no justification :p It should throw. And any new C++ program should assume so. There isn't much to do when you run out of memory anyway... so writing a lot of code to partially handle it is a waste IMO and makes your code harder to read.
 
operator[] is the only function in your class that needs to return type Complex. In fact, it should return a reference to type Complex. This is because the value returned by operator[] should be able to be used as both an rvalue and an lvalue. And of course, you should overload operator[] to also handle const-ness correctly.

new never throws in VC++ for backwards compatibility reasons. That's just the way it is. I would prefer that there was a compiler switch to toggle that behavior. Typically, I would prefer that new throw, since in this day and age of virtual memory, a failure to allocate memory truly is an exceptional condition. But, its understandable that new didn't throw in the past, since at that time not all platforms that C++ was commonly used on supported virtual memory. And, in those cases a failure to allocate memory was too common to be considered exceptional. And in fact, we are returning to those days in a sense, since embedded devices are becoming so popular, and those kinds of devices tend to have limited resources.
 


I thought VC++ didn't throw exceptions from <span style="font-family: monospace;">new</span> because it was so damn old, and at the time it was created such behaviour wasn't standardized (and they, rightly IMO, didn't wish to change the behaviour in an important way like this in a Service Pack). VS.NET does throw an exception, unless you use the <span style="font-family: monospace;">nothrow</span> version of <span style="font-family: monospace;">new</span>.





So this program:


Code:
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
	const size_t s = 0xffffffff;
	cout << "allocating " << s * sizeof(char) << " bytes" << endl;
	char* a = NULL;
	try
	{
		cout << "new" << endl;
		a = new char[s];
		cout << (int)a << endl;
		delete [] a;
	}
	catch(bad_alloc e)
	{
		cout << e.what() << endl;
	}
	try
	{
		cout << "new(nothrow)" << endl;
		a = new(nothrow) char[s];
		cout << (int)a << endl;
		delete [] a;
	}
	catch(bad_alloc e)
	{
		cout << e.what() << endl;
	}
}


produces this output:


Code:
allocating 4294967295 bytes
new
bad allocation
new(nothrow)
0
 

Crazyguy

Seniorius Lurkius
41
These are the errors i'm getting... i corrected the [] operator... i'm missing something basic here but i'm not sure what it is???

--------------------Configuration: CArray - Win32 Debug--------------------
Compiling...
CArray.cpp
carray.h(21) : error C2143: syntax error : missing ';' before '&'
carray.h(21) : error C2501: 'Complex' : missing storage-class or type specifiers
carray.h(21) : error C2501: '[]' : missing storage-class or type specifiers
carray.h(22) : error C2143: syntax error : missing ';' before '&'
carray.h(22) : error C2501: '[]' : missing storage-class or type specifiers
carray.h(26) : error C2143: syntax error : missing ';' before '*'
carray.h(26) : error C2501: 'Complex' : missing storage-class or type specifiers
carray.h(26) : error C2501: 'ptr' : missing storage-class or type specifiers
carray.cpp(11) : error C2758: 'Complex' : must be initialized in constructor base/member initializer list
carray.h(22) : see declaration of 'Complex'
carray.cpp(14) : error C2065: 'ptr' : undeclared identifier
carray.cpp(14) : error C2061: syntax error : identifier 'Complex'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : error C2143: syntax error : missing ';' before '{'
carray.cpp(16) : fatal error C1003: error count exceeds 100; stopping compilation
Error executing cl.exe.

CArray.obj - 102 error(s), 0 warning(s)
 
The errors your getting seem to stem from the fact that you need to include "complex.h" or what file declares your Complex class. The compiler needs this info to evaluate what a Complex& is.

A forward declaration of class Complex in your CArray header file should clear up those errors. If you haven't used forward declarations before, here's an example:
code:<HR>
Code:
class Complex;<P>class CArray
{
  ...
};
 
I haven't used VC++ 7 yet, but if new finally throws I'll be a happy man. On a bit a side note, I haven't seen any mention of how VC++ 7 addresses some the C++ conformance issue the VC++ 6 had. Especially, wrt partial specialization and member templates (including friends). Any way you could share any experience you've had using these features with VC++ 7?
 
Status
Not open for further replies.