c++ object constructor question


 
Thread Tools Search this Thread
Top Forums Programming c++ object constructor question
# 1  
Old 06-26-2010
c++ object constructor question

I have the following code

Code:
class Param{
    public:
    Param(int aa, int bb){
        a=aa;
        b=bb;
    }
int a,b;
};

void function(Param);

Code:
int main(){

   function(2,3);
    return 0;
}

Code:
void function(Param par){
    cout<<par.a;
}

, and when I run it, I get the following message error:

Code:
.../main.cpp|21|error: conversion from ‘int’ to non-scalar type ‘Param’ requested|

I know the problem is that function should have been called with an object from Param, but I was expecting that the constructor Param(int , int) would do the job.
What is wrong with my assumption, and how could I fix this problem?

thank you in advance!!
santiagorf

Last edited by santiagorf; 06-26-2010 at 04:45 PM..
# 2  
Old 06-26-2010
Quote:
Originally Posted by santiagorf
I know the problem is that function should have been called with an object from Param, but I was expecting that the constructor Param(int , int) would do the job.
It might be if you'd actually called it. You're just feeding it 2,3 not Param(2,3).
# 3  
Old 06-26-2010
Thanks Corona688 for your prompt replay, and in fact if I call as
Code:
function( Param(2,3))

I will have the desired result. However, what I'm trying to generate is the behavior of the code below taken from "Teach yourself in 21 days".

Though the code is a little long there are few steps that are important (in black).

In the main function there is a call to a method SetFirstName from the class Employee
Code:
 Edie.SetFirstName("Edythe");

that pases as parameter a constant character string, but SetFirstName only requires a constant string reference.
This problem is solved by the String constructor
Code:
String(const char *const);

that takes a constant character string and makes a string.

So, in my code I was expecting to have the constructor
Code:
Param(int aa, int bb)

the same behavior as
Code:
String(const char *const);

, but there is something I don't see.



Code:
   class String
   {
      public:
         // constructors
         String();
          String(const char *const);
          String(const String &);
         ~String();

         // overloaded operators
         char & operator[](int offset);
         char operator[](int offset) const;
         String operator+(const String&);
         void operator+=(const String&);
         String & operator= (const String &);

         // General accessors
         int GetLen()const { return itsLen; }
         const char * GetString() const { return itsString; }
         // static int ConstructorCount;

      private:
         String (int);         // private constructor
         char * itsString;
         unsigned short itsLen;

   };

   // default constructor creates string of 0 bytes
   String::String()
   {
      itsString = new char[1];
      itsString[0] = '\0';
      itsLen=0;
      // cout << "\tDefault string constructor\n";
      // ConstructorCount++;
   }

   // private (helper) constructor, used only by
   // class methods for creating a new string of
   // required size.  Null filled.
   String::String(int len)
   {
      itsString = new char[len+1];
      for (int i = 0; i<=len; i++)
         itsString[i] = '\0';
      itsLen=len;
      // cout << "\tString(int) constructor\n";
      // ConstructorCount++;
   }

   // Converts a character array to a String
   String::String(const char * const cString)
   {
      itsLen = strlen(cString);
      itsString = new char[itsLen+1];
      for (int i = 0; i<itsLen; i++)
         itsString[i] = cString[i];
      itsString[itsLen]='\0';
      // cout << "\tString(char*) constructor\n";
      // ConstructorCount++;
   }

   // copy constructor
   String::String (const String & rhs)
   {
      itsLen=rhs.GetLen();
      itsString = new char[itsLen+1];
      for (int i = 0; i<itsLen;i++)
         itsString[i] = rhs[i];
      itsString[itsLen] = '\0';
      // cout << "\tString(String&) constructor\n";
      // ConstructorCount++;
   }

   // destructor, frees allocated memory
   String::~String ()
   {
      delete [] itsString;
      itsLen = 0;
      // cout << "\tString destructor\n";
   }

   // operator equals, frees existing memory
   // then copies string and size
   String& String::operator=(const String & rhs)
   {
      if (this == &rhs)
         return *this;
      delete [] itsString;
      itsLen=rhs.GetLen();
      itsString = new char[itsLen+1];
      for (int i = 0; i<itsLen;i++)
         itsString[i] = rhs[i];
      itsString[itsLen] = '\0';
      return *this;
      // cout << "\tString operator=\n";
   }

   //non constant offset operator, returns
   // reference to character so it can be
   // changed!
   char & String::operator[](int offset)
   {
      if (offset > itsLen)
         return itsString[itsLen-1];
      else
         return itsString[offset];
   }

   // constant offset operator for use
   // on const objects (see copy constructor!)
   char String::operator[](int offset) const
   {
      if (offset > itsLen)
         return itsString[itsLen-1];
      else
         return itsString[offset];
   }

   // creates a new string by adding current
   // string to rhs
   String String::operator+(const String& rhs)
   {
      int  totalLen = itsLen + rhs.GetLen();
      String temp(totalLen);
      int i, j;
      for (i = 0; i<itsLen; i++)
         temp[i] = itsString[i];
      for (j = 0; j<rhs.GetLen(); j++, i++)
         temp[i] = rhs[j];
      temp[totalLen]='\0';
      return temp;
   }

   // changes current string, returns nothing
   void String::operator+=(const String& rhs)
   {
      unsigned short rhsLen = rhs.GetLen();
      unsigned short totalLen = itsLen + rhsLen;
      String  temp(totalLen);
      for (int i = 0; i<itsLen; i++)
         temp[i] = itsString[i];
      for (int j = 0; j<rhs.GetLen(); j++, i++)
         temp[i] = rhs[i-itsLen];
      temp[totalLen]='\0';
      *this = temp;
   }

 // int String::ConstructorCount = 0;

Code:
   class Employee
   {

   public:
      Employee();
      Employee(char *, char *, char *, long);
      ~Employee();
      Employee(const Employee&);
      Employee & operator= (const Employee &);

      const String & GetFirstName() const
         { return itsFirstName; }
      const String & GetLastName() const { return itsLastName; }
      const String & GetAddress() const { return itsAddress; }
      long GetSalary() const { return itsSalary; }

      void SetFirstName(const String & fName)
          { itsFirstName = fName; }
      void SetLastName(const String & lName)
         { itsLastName = lName; }
      void SetAddress(const String & address)
           { itsAddress = address; }
      void SetSalary(long salary) { itsSalary = salary; }
   private:
      String    itsFirstName;
      String    itsLastName;
      String    itsAddress;
      long      itsSalary;
   };

   Employee::Employee():
      itsFirstName(""),
      itsLastName(""),
      itsAddress(""),
      itsSalary(0)
   {}

   Employee::Employee(char * firstName, char * lastName,
      char * address, long salary):
      itsFirstName(firstName),
      itsLastName(lastName),
      itsAddress(address),
      itsSalary(salary)
   {}

   Employee::Employee(const Employee & rhs):
      itsFirstName(rhs.GetFirstName()),
      itsLastName(rhs.GetLastName()),
      itsAddress(rhs.GetAddress()),
      itsSalary(rhs.GetSalary())
   {}

   Employee::~Employee() {}

   Employee & Employee::operator= (const Employee & rhs)
   {
      if (this == &rhs)
         return *this;

      itsFirstName = rhs.GetFirstName();
      itsLastName = rhs.GetLastName();
      itsAddress = rhs.GetAddress();
      itsSalary = rhs.GetSalary();

      return *this;
   }

Code:
   int main()
   {
      Employee Edie("Jane","Doe","1461 Shore Parkway", 20000);

      Edie.SetFirstName("Edythe");


     cout << Edie.GetFirstName().GetString();

    return 0;
}

# 4  
Old 06-27-2010
I don't see any similarity in design or inheritance between what you're trying to do and and the example you quote... I don't think the constructor is what lets it do that, are you sure that's the complete code? No external operator functions? Also: You can't cast one value into two values.

Last edited by Corona688; 06-27-2010 at 12:45 AM..
# 5  
Old 06-28-2010
Quote:
Originally Posted by Corona688
I don't see any similarity in design or inheritance between what you're trying to do and and the example you quote... I don't think the constructor is what lets it do that, are you sure that's the complete code? No external operator functions? Also: You can't cast one value into two values.
The code is taken from:
PHP Code:
http://newdata.box.sk/bx/c/htm/ch15.htm 
see listing 15.1 and 15.2. Most of the code is exactly the same as the one I posted with the exception of the main function. According to the book -and I debugged it in order to verify it- this behavior is due to the constructor from String.
# 6  
Old 06-29-2010
I stand corrected, then. You still can't cast one parameter into two parameters, though. It could take a single class that had two members.

A better way to handle this case would be to overload function itself -- make another function of the same name that does in fact take two integers.
# 7  
Old 06-30-2010
Quote:
Originally Posted by santiagorf
I have the following code

Code:
class Param{
    public:
    Param(int aa, int bb){
        a=aa;
        b=bb;
    }
int a,b;
};

void function(Param);

Code:
int main(){

   function(2,3);
    return 0;
}

Code:
void function(Param par){
    cout<<par.a;
}

, and when I run it, I get the following message error:

Code:
.../main.cpp|21|error: conversion from ‘int' to non-scalar type ‘Param' requested|

I know the problem is that function should have been called with an object from Param, but I was expecting that the constructor Param(int , int) would do the job.
What is wrong with my assumption, and how could I fix this problem?

thank you in advance!!
santiagorf
This is known as implicit conversion and for constructors it works if it has a single argument only.

If you have multiple arguments and want to make use of the implicit conversion, then you need a constructor having default values.

Something like...

Code:
class Param{
public:
    Param(int a, int b = 0) : _a(a), _b(b) {}
int _a,_b;
};
void function(Param par)
{
   cout<<par.a;
}
int main(){

   function(2);
   return 0;
}

Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Programming

How to initialize an object with another object of different class?

How to initialize an object of class say "A", with an object of type say "B". The following code give the error message "error: conversion from âAâ to non-scalar type âBâ requested" #include <iostream> using namespace std; class B; class A{ public: A() { cout <<"\nA()" << endl; } ... (1 Reply)
Discussion started by: techmonk
1 Replies

2. Programming

Constructor?

I am learning about C++ and today am reading concepts for Constructor but it seems a bit difficult to grab it fully. Please anyone explain in simple words about Constructor? (1 Reply)
Discussion started by: ggiwebsinfo
1 Replies

3. Programming

Doubts on C++ copy constructor concept

Hi, If I run the following program class A { public: A() { cout << "default" << endl; } A(const A&) { cout << "copy" << endl; } }; A tmp; A fun() { return tmp; } A test() { A tmp; cout << &tmp << endl; return tmp; } (1 Reply)
Discussion started by: royalibrahim
1 Replies

4. Programming

Shared Object Question

Hello, I am new to programming shared objects and I was hoping someone could tell me if what I want to do is possible, or else lead me in the right direction. I have a main program that contains an abstract base class. I also have a subclass that I'm compiling as a shared object. The subclass... (13 Replies)
Discussion started by: dorik
13 Replies

5. Programming

question about function object

I have a code as following: #include <iostream> #include <algorithm> #include <list> using namespace std; //the class Nth is a predicates class Nth{ private: int nth; int count; public: Nth(int n):nth(n),count(0){} bool operator()(int){ ... (2 Replies)
Discussion started by: homeboy
2 Replies

6. UNIX for Dummies Questions & Answers

Object reference not set to an instance of an object

I am new to PHP and UNIX. I am using Apache to do my testing on a Windows Vista machine. I am getting this error when I am trying to connect to a web service. I did a search and did not see any posts that pertain to this. Here is my function: <?php function TRECSend($a, $b, $c, $d,... (0 Replies)
Discussion started by: EddiRae
0 Replies

7. Programming

Doubt regarding Copy Constructor and return value

Hi All, I have made the simple following program :- #include <string> #include <iostream> using namespace std; class A{ private: int val; public : A(){cout<<"In A()"<<endl;} A (const A& aa) { cout<<"In copy c'tor"<<endl; } }; A f(... (1 Reply)
Discussion started by: shubhranshu
1 Replies

8. Programming

how do you handle a constructor and destructor that fail

helo i m new in c++ on linux can u tell me with an simple example that how do you handle constructor and destructor that fail? Regards, Amit (4 Replies)
Discussion started by: amitpansuria
4 Replies

9. Programming

why constructor cannot be virtual

helo i read many books but i cant find the proper answer that why constructor cannot be virtual can u explain me in simple term that why constructor cannot be virtual Regards, Amit (2 Replies)
Discussion started by: amitpansuria
2 Replies

10. UNIX for Dummies Questions & Answers

Constructor problem

Hi guys I am new to these forums but since I am taking a class at college I would appreciate any help that is possible for this program. My instructor said that when its complete the program should be able to store all 3 fields instead of just 1. public class Greeter2Test { public static... (4 Replies)
Discussion started by: woot4moo
4 Replies
Login or Register to Ask a Question