Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Problem with Classes and Constructors

Posted on 2007-10-12
6
Medium Priority
?
371 Views
Last Modified: 2008-01-09
I am working on a program that is supposed to have a class header, a class implementation file, and a test file.  I managed to get al of that done in one day, but now I am stuck.  I keep getting this error message, but i can't understand what I am doing wrong. The class is supposed to have a bunch of functions that perform mathematical calculations, i.e. is something prime, perfect, etc.  I cannot compile it.  I keep getting the error "c10pp02.cpp(23) : error C2512: 'MyInt' : no appropriate default constructor available"

Here is my class code:
#include <iostream>

    using namespace std;

    class MyInt
    {
       
            public:

            //constructor
            MyInt(int);
     
            //get value from data file
            int getNumValue() const;

            //set value of numValue
            void setNumValue(int);

            //destructor
            ~MyInt();


            //finds out if the value is a multiple of 7 11 or 13
            bool isMultipleOf7or11or13(int);

            //finds out if the sum of all of the digits in the value is even
            bool isSumOfDigitsEven(int);

            //finds out the square root of the number
            double squareRoot(int);

            //finds out whether the value is only divisible by itself and 1
            bool isPrime(int);

            //finds out whether the sum of the factors of the value is equal to value
            bool isPerfect(int);
            
      private:
            
            


    };


Here is my class implementation code:

#include <cstring>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <cmath>
#include "MyInt.H"
#include <cstdlib>


using namespace std;

int myInt;

MyInt::MyInt(int myInt)
      {
            myInt = 0;
      }


MyInt::~MyInt()
{
      cout << "This is the MyInt destructor" << endl;
}

int MyInt::getNumValue() const
{
      
      return myInt;
}

void MyInt::setNumValue(int myInt)
{
      if (!(myInt >= 0))
      {
            
            cout << "This value is out of range." << endl;
            myInt = 0;
      }
}
bool MyInt::isMultipleOf7or11or13(int myInt)
{
      if ((myInt%7 == 0)|| (myInt%11 == 0) || (myInt%11 == 0))
            {
                  return true;
            }
      else
            {
                  return false;
            }
}
bool MyInt::isSumOfDigitsEven(int myInt)
{
      int temp = 0;
      int sum = 0;
      char *num2Char;//holds the value of the int converted to char
      do
      {
            itoa( myInt, num2Char, 10);//gets value of one digit and sets it to char so that the digits can be separated to add the sum
            temp = atoi(num2Char);

            sum += temp;
      }while (!" ");
      
      if (sum%2 == 0)
      {
            return true;
      }
      else
      {
            return false;
      }
}

double MyInt::squareRoot(int myInt)
{
      double sqRt = double(myInt) / 2;
      const double tolerance = .005;//tolerance for error

      do sqRt = (sqRt + double(myInt) / sqRt) / 2;
      while( abs(sqRt * sqRt - double(myInt)) > tolerance);
      
      return sqRt;
}
bool MyInt::isPrime(int myInt)
{
      if ((myInt%2 == 0)|| (myInt%3 == 0) || (myInt%5 == 0))
      {
            return false;
      }
      else
      {
            return true;
      }
}
bool MyInt::isPerfect(int myInt)
{
      int sum = 0;

      for (int i = 1; i < myInt; i++)
      {
            if (myInt%i == 0)
            {
                  sum+=i;
            }
            else
            {
                  sum = 0;
            }
      }
      if (sum == myInt)
      {
            return true;
      }
      else
      {
            return false;
      }
}

and finally here is my test code:#include <cstring>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <cmath>
#include "MyInt.H"
#include <cstdlib>


using namespace std;

void openFiles (ifstream& inFile, ofstream& outFile);


int main()
{
      MyInt myNumber;

      ifstream ins;
      ofstream outs;
      int myNumValue;

      openFiles(ins, outs);
      

      myNumber.getNumValue();

      myNumber.setNumValue(myNumValue);

      
      
      if (!(myNumber.isMultipleOf7or11or13(myNumValue)))
      {
            outs << myNumValue << " : "  << "Is not a multiple of 7, 11, or 13." << endl;
      }
      else
      {
            outs << myNumValue << " : "  << "Is a multiple of 7, 11, or 13." << endl;
      }


      if (!(myNumber.isSumOfDigitsEven(myNumValue)))
      {
            outs << myNumValue << " : " << "Some of digits is not even." << endl;
      }
      else
      {
            outs << myNumValue << " : " << "Some of digits is even." << endl;
      }      

      outs << myNumValue << " : "  << "The square root is " << myNumber.squareRoot(myNumValue) << endl;
      
      if (!(myNumber.isPrime(myNumValue)))
      {
            outs << myNumValue << " : "  << "Is not prime." << endl;
      }
      else
      {
                  outs << myNumValue << " : "  << "Is prime." << endl;
      }
      

      if (!(myNumber.isPerfect(myNumValue)))
      {
            outs << myNumValue << " : "  << "Is not perfect." << endl;
      }
      else
      {
            outs << myNumValue << " : "  << "Is perfect." << endl;
      }
      outs << endl;
      ins.close();
      outs.close();

      return 0;

}
void openFiles (ifstream& inFile, ofstream& outFile)
{
      string fileName;

      cout << "Enter name of the input file" << endl;
      cin >> fileName;

      inFile.open (fileName.c_str());
      if (inFile.fail())
      {
            cout << "Could not open file " << fileName << endl;
            cout << "Exiting program." << endl;
            exit (0);
      }
      cout << "Enter name of the output file" << endl;
      cin >> fileName;

      outFile.open (fileName.c_str());
      if (outFile.fail())
      {
            cout << "Could not open file " << fileName << endl;
            cout << "Exiting program." << endl;
            exit (0);
      }
}



I am getting warnings and I would welcome assistance with the warnings as well.  Here is a copy of the log:
c10pp02.cpp(23) : error C2512: 'MyInt' : no appropriate default constructor available
myint.cpp(63) : warning C4996: 'itoa' was declared deprecated
myint.cpp(63) : warning C4700: uninitialized local variable 'num2Char' used


This is due in about forty five minutes, so I would appreciate some speedy help.  

Also, some things you should know.  My instructor said "Write a one-parameter constructor to initialize the myInt attribute (data member)"  "Write a public getter and a public setter to set and retrieve the value of myInt. "


Please help?
0
Comment
Question by:yasmeens
  • 4
6 Comments
 
LVL 15

Expert Comment

by:efn
ID: 20070211
A default constructor is one that doesn't take any parameter.  Sometimes the compiler will make one for you if you don't declare one yourself.  In your case, you declared a constructor that takes one parameter.

            //constructor
            MyInt(int);

When you do that, the compiler will not supply a default constructor, since you are taking charge of construction.

When you write a declaration like this:

MyInt myNumber;

you are not supplying a constructor argument, so the compiler would have to use a default constructor to construct the object.  But because you declared a constructor with a parameter, the class has not default constructor, so the compiler is telling you it can't construct this object.

So your choices are:

1) You can declare and define a default constructor.  Then the compiler will accept the declaration of myNumber.

2) You can change the declaration of myNumber so it has a constructor parameter.  Then it can use the constructor you already have.

Because you are in a hurry, I will post this before writing more.
0
 
LVL 15

Expert Comment

by:efn
ID: 20070223
>> My instructor said "Write a one-parameter constructor to initialize the myInt attribute (data member)"

MyInt::MyInt(int myInt)
      {
            myInt = 0;
      }

This just sets the temporary parameter myInt to zero.  myInt is not an attribute (data member).  You need to declare a data member in the class, and then this constructor should assign its parameter to the data member.  To avoid confusion, use different names for the parameter and the data member--don't call them both "myInt".
0
 
LVL 15

Expert Comment

by:efn
ID: 20070246
     char *num2Char;//holds the value of the int converted to char
      do
      {
            itoa( myInt, num2Char, 10);//gets value of one digit and sets it to char so that the digits can be separated to add the sum

myint.cpp(63) : warning C4996: 'itoa' was declared deprecated
myint.cpp(63) : warning C4700: uninitialized local variable 'num2Char' used

The first warning means that the itoa function may be removed from the compiler library some day, so if you don't want your program to break when that happens, you shouldn't use that function.  This is unlikely to happen during the lifespan of your assignment, so you don't have to worry about it unless you can't stand warnings.  If that is the case, there are other alternatives to itoa.

The second warning is more serious.  The second parameter to itoa is supposed to point to an array of characters where the function can write its output.  Your program is passing an uninitialized pointer that could point to anything.  You don't want the function writing its output at some random location:  that can break your program in ways that are difficult to diagnose.  You should instead declare a sufficiently large character array and pass it to itoa instead of the pointer.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:yasmeens
ID: 20070270
OK I think I got the constructor thing fixed, but since I tried to pass an array to itoa, I got another error message:
Here is my code again:

Class

#include <iostream>

    using namespace std;

    class MyInt
    {
       
            public:

                  int myNum;

            //constructor
            MyInt(int);
     
            //get value from data file
            int getNumValue() const;

            //set value of numValue
            void setNumValue(int);

            //destructor
            ~MyInt();


            //finds out if the value is a multiple of 7 11 or 13
            bool isMultipleOf7or11or13(int);

            //finds out if the sum of all of the digits in the value is even
            bool isSumOfDigitsEven(int);

            //finds out the square root of the number
            double squareRoot(int);

            //finds out whether the value is only divisible by itself and 1
            bool isPrime(int);

            //finds out whether the sum of the factors of the value is equal to value
            bool isPerfect(int);
           
      private:
};


class implementation file

#include <cstring>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <cmath>
#include "MyInt.H"
#include <cstdlib>


using namespace std;

int myNum;

MyInt::MyInt(int myNumValue)
      {
              myNum = myNumValue;
      }


MyInt::~MyInt()
{
      cout << "This is the MyInt destructor" << endl;
}

int MyInt::getNumValue() const
{
     
      return myNum;
}

void MyInt::setNumValue(int myNum)
{
      if (!(myNum >= 0))
      {
           
            cout << "This value is out of range." << endl;
            myNum = 0;
      }
}
bool MyInt::isMultipleOf7or11or13(int myNum)
{
      if ((myNum%7 == 0)|| (myNum%11 == 0) || (myNum%11 == 0))
            {
                  return true;
            }
      else
            {
                  return false;
            }
}
bool MyInt::isSumOfDigitsEven(int myNum)
{
      int temp = 0;
      int sum = 0;
        int sub = 0;
      char num2Char[10];//holds the value of the int converted to char
      do
      {
                itoa( myNum, num2Char[sub], 10);//gets value of one digit and sets it to char so that the digits can be separated to add the sum
            temp = atoi(num2Char[sub]);
                  sub++;

            sum += temp;
      }while (!" ");
     
      if (sum%2 == 0)
      {
            return true;
      }
      else
      {
            return false;
      }
}

double MyInt::squareRoot(int myNum)
{
      double sqRt = double(myNum) / 2;
      const double tolerance = .005;//tolerance for error

      do sqRt = (sqRt + double(myNum) / sqRt) / 2;
      while( abs(sqRt * sqRt - double(myNum)) > tolerance);
     
      return sqRt;
}
bool MyInt::isPrime(int myNum)
{
      if ((myNum%2 == 0)|| (myNum%3 == 0) || (myNum%5 == 0))
      {
            return false;
      }
      else
      {
            return true;
      }
}
bool MyInt::isPerfect(int myNum)
{
      int sum = 0;

      for (int i = 1; i < myNum; i++)
      {
            if (myNum%i == 0)
            {
                  sum+=i;
            }
            else
            {
                  sum = 0;
            }
      }
      if (sum == myNum)
      {
            return true;
      }
      else
      {
            return false;
      }
}


test file

#include <sstream>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <cmath>
#include "MyInt.H"
#include <cstdlib>


using namespace std;

void openFiles (ifstream& inFile, ofstream& outFile);


int main()
{
     

      ifstream ins;
      ofstream outs;
      int myNumValue = 0;

      openFiles(ins, outs);
      MyInt myNumber(myNumValue);

      myNumber.getNumValue();

      myNumber.setNumValue(myNumValue);

     
     
      if (!(myNumber.isMultipleOf7or11or13(myNumValue)))
      {
            outs << myNumValue << " : "  << "Is not a multiple of 7, 11, or 13." << endl;
      }
      else
      {
            outs << myNumValue << " : "  << "Is a multiple of 7, 11, or 13." << endl;
      }


      if (!(myNumber.isSumOfDigitsEven(myNumValue)))
      {
            outs << myNumValue << " : " << "Some of digits is not even." << endl;
      }
      else
      {
            outs << myNumValue << " : " << "Some of digits is even." << endl;
      }      

      outs << myNumValue << " : "  << "The square root is " << myNumber.squareRoot(myNumValue) << endl;
     
      if (!(myNumber.isPrime(myNumValue)))
      {
            outs << myNumValue << " : "  << "Is not prime." << endl;
      }
      else
      {
                  outs << myNumValue << " : "  << "Is prime." << endl;
      }
     

      if (!(myNumber.isPerfect(myNumValue)))
      {
            outs << myNumValue << " : "  << "Is not perfect." << endl;
      }
      else
      {
            outs << myNumValue << " : "  << "Is perfect." << endl;
      }
      outs << endl;
      ins.close();
      outs.close();

      return 0;

}
void openFiles (ifstream& inFile, ofstream& outFile)
{
      string fileName;

      cout << "Enter name of the input file" << endl;
      cin >> fileName;

      inFile.open (fileName.c_str());
      if (inFile.fail())
      {
            cout << "Could not open file " << fileName << endl;
            cout << "Exiting program." << endl;
            exit (0);
      }
      cout << "Enter name of the output file" << endl;
      cin >> fileName;

      outFile.open (fileName.c_str());
      if (outFile.fail())
      {
            cout << "Could not open file " << fileName << endl;
            cout << "Exiting program." << endl;
            exit (0);
      }
}


The error messages are as follows:

myint.cpp(64) : error C2664: 'itoa' : cannot convert parameter 2 from 'char' to 'char *'
myint.cpp(65) : error C2664: 'atoi' : cannot convert parameter 1 from 'char' to 'const char *'

0
 
LVL 15

Assisted Solution

by:efn
efn earned 248 total points
ID: 20070318
The parameters are declared to be pointers to characters.  You can pass an array of characters as one of these parameters and it will automatically get converted to a pointer.

num2Char is an array.  You can pass it by name to itoa and atoi.

num2Char[sub] is a character element of the array.  It's a character.  It's neither an array nor a pointer, so the compiler won't let you pass it as a pointer parameter.
0
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 252 total points
ID: 20078657
>>>> bool MyInt::isSumOfDigitsEven(int myNum)
the implementation of that function is wrong. You neither should use itoa nor a char array. Moreover, a 'do while' should aonly be done if you need to process the loop at least once. That isn't the case for myNum == 0. Finally, the loop condition (!" ") is very  wrong. " " is a literal and always is != NULL. So !" " never is true.

bool MyInt::isSumOfDigitsEven(int myNum)
{
      // int temp = 0; // no temps needed
      int sum = 0;
      //  int sub = 0; // no temps needed

      int digit = 0; // you may as well use a int for any digit

      while (myNum != 0)   // we extract any digit beginning 'at end'
                                        // finally mynum is 0 and we are done
      {
                // itoa( myNum, num2Char[sub], 10            
                // temp = atoi(num2Char[sub]);
            digit = myNum%10;   // extract the last digit
            sum += digit;             // add to sum
            myNum /= 10;            // divide by 10 to actually extracting it
      }
      ....
}

You see, no char, no itoa, no atoi.

Regards, Alex

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
Suggested Courses

564 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question