Wrox Programmer Forums
|
C++ Programming General discussions for the C++ language. For questions specific to Microsoft's Visual C++ variant, see the Visual C++ forum instead.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the C++ Programming section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
  #1 (permalink)  
Old April 26th, 2004, 03:15 AM
Authorized User
 
Join Date: Mar 2004
Posts: 33
Thanks: 0
Thanked 1 Time in 1 Post
Default COPY CONSTRUCTORS

I really need help.

i previously posted a problem regarding aggregation and inheritance. Look at the user defined constructor and please tell me if im correct with the Publisher object. There is a main file which calls the BookItem constructor like this:
BookItem text1("Author", "Title", Publisher("Publisher's name")), 2002);
I dont know how to create the Set and GetPublisher() functions, i want to be able to set and get the Publisher's name. Can someone please help me. Someone was helping me but i still cant get it right.
I have a
SetPublisher(Publisher pubTemp){
delete pub;
pub = new Publisher(pubTemp);
//initialise the copy constructor
}
The GetPublisher returns a string or a class type, not sure?
i done a bit of extra work on the assignment operator overloading as well, not sure if thats right, too
please, get me out of this mess????

#include<iostream>
#include<string>

   using namespace std;

#include "BookItem.h"
#include "StockItem.h"


// USER DEFINED CONSTRUCTOR

    BookItem::BookItem(string Authors, const string &Title, Publisher
     pubTemp, int Year = 0)
    :StockItem(Title)
    {
     pub = new Publisher(pubTemp);

      this->SetAuthors(Authors);
      this->SetTitle(Title);
// this->SetPublisher(pub);
      this->SetYear(Year);
   }

   string BookItem::GetAuthors() const
   {
      return(this->Authors);
   }

    string BookItem::GetTitle() const
   {
      return(this->Title);
   }

     string BookItem::GetPublisher() const
       {
         return("");
        }

    int BookItem::GetYear() const
   {
      return(this->Year);
   }

    void BookItem::SetAuthors(string Authors)
   {
      this->Authors = Authors;
   }

    void BookItem::SetTitle(const string &Title)
   {
      this->Title = Title;
   }

   void BookItem::SetPublisher(Publisher pubTemp)
   {
      delete pub;
      pub = new Publisher(pubTemp);

   }


   void BookItem::SetYear(int Year)
   {
      this->Year = Year;
   }

   //COPY CONSTRUCTOR
   BookItem::BookItem(const BookItem& bkObject)
     :StockItem(bkObject), Authors(bkObject.GetAuthors()),Title(bkObject.GetT itle()),
          pub(bkObject.pub), Year(bkObject.GetYear())
   {

   }

   BookItem BookItem::operator=(const BookItem& temp)
   {

  if (this == &temp)
  {
  // IF THE RIGHT SIDE IS THE SAME AS THE LEFT SIDE
     return *this;
  }
     else
     {
     delete pub;
     Authors = temp.Authors;
     Title = temp.Title;
     pub = temp.pub;
     Year = temp.Year;

   return *this;
   }
   }

void BookItem::RecordPurchase(const int NumberPurchased,
const double &CostPrice)
{
double num = NumberPurchased * CostPrice;

SetTotalCost(num);
SetCostPrice(CostPrice);
SetNumberSold(NumberPurchased);

}


BookItem::~BookItem()
{
delete pub;
}


void BookItem::Print()
{
cout << endl;
cout << "Stock Item: " << GetTitle() << endl;

cout << "\tNumber Sold " << "\t- " << GetNumberSold() << endl;
cout << "\tTotal Revenue " << "\t- " << GetTotalRevenue() << endl;
cout << "\tTotal Cost " << "\t- " << GetTotalCost() << endl;
//cout << "\tAverage Profit " << "\t- " << GetAverageProfit() << endl;
cout << "\tAuthors " << "\t- " << GetAuthors() << endl;
cout << "\tPublisher " << "\t- " << GetPublisher() << endl;
}
__________________
gbilios
Reply With Quote
  #2 (permalink)  
Old April 27th, 2004, 05:50 PM
Friend of Wrox
 
Join Date: Jun 2003
Posts: 836
Thanks: 0
Thanked 0 Times in 0 Posts
Default

No, it doesn't look quite right. A class constructor is called upon an instance of the class, so that instance has access to private members (variables and functions) defined in that class.

As such, you can write a copy constructor like this:

class Foo
{
private:
   string my_string;
   int my_int;

public:
   Foo(const Foo & other)
      : my_string(other.my_string) , my_int(other.my_int)
   {
   }
};

See how I accessed the other's privates directly? I didn't have to call accessor functions like getMyString() or getMyInt().


Quote:
quote:
The GetPublisher returns a string or a class type, not sure?
Well, the name of the function implies that you're returning a Publisher object. You need to be careful that the code calling getPublisher() doesn't mess up the memory allocated for the original object. If you return a Publisher object, odds are you're making a copy of the original object via the assignment operator. That is:

Publisher pub = someBookItem.GetPublisher();


To use the copy constructor, you'd do this:

Publisher pub(someBookItem.GetPublisher());


Either way creates a copy of the original so that when the copy goes out of scope, the original is still in tact.


one more thing -- your SetPublisher() function deletes the existing publisher pointer without checking if it's NULL. It might be best for you to implement an operator=() function to handle assignment. That way, you won't have to rely on managing pointers to objects, you can just deal with objects themselves.

The operator=() declaration would look a lot like your copy constructor. To use the Foo example class above:

class Foo
{
   ...

   Foo& operator=(const Foo & other)
   {
      my_string = other.my_string;
      my_int = other.my_int;
   }
};


Finally, notice that I don't use "this->" anywhere. Within the context of an object instance's member functions, "this->" is implicit when accessing that instance's member variables. Granted, one might argue that it makes the code more legible and obvious. However, I disagree: If you adopt a variable naming convention that identifies member variables, then you don't need "this->". that's 6 extra characters on each line of code that you don't need. This might not seem like a lot, but keep in mind that most institutions (companies, schools, etc) impose formatting rules for code (aka a "coding standard"). If you are not supposed to have lines extend past 80 characters, then it makes sense to be as consise as possible.

For example, many people use the "m_" prefix to member variables. Other people prefer a trailing underscore. Here's both in our Foo example:

// m_

class Foo
{
private:
   string m_my_string;
   int m_my_int;
};


// trailing underscore
class Foo
{
private:
   string my_string_;
   int my_int_;
};


It becomes immediately apparent, therefore, when you're acecssing a member variable, and "this->" becomes unnecessary. Local variables do not include these characteristics, so it's easy to distinguish the two.


Take care,

Nik
http://www.bigaction.org/
Reply With Quote
  #3 (permalink)  
Old April 27th, 2004, 10:50 PM
Authorized User
 
Join Date: Mar 2004
Posts: 33
Thanks: 0
Thanked 1 Time in 1 Post
Default

thanks
Reply With Quote
  #4 (permalink)  
Old April 28th, 2004, 07:22 PM
Friend of Wrox
 
Join Date: Jun 2003
Posts: 836
Thanks: 0
Thanked 0 Times in 0 Posts
Default

np

Take care,

Nik
http://www.bigaction.org/
Reply With Quote
  #5 (permalink)  
Old April 30th, 2004, 02:51 AM
Authorized User
 
Join Date: Mar 2004
Posts: 33
Thanks: 0
Thanked 1 Time in 1 Post
Default

This modified the copy constructor as follows

//COPY CONSTRUCTOR
   BookItem::BookItem(const BookItem& bkObject)
    :StockItem(bkObject), Authors(bkObject.GetAuthors()),Title(bkObject.GetT itle()),
        pub(new Publisher(bkObject.pub->GetName())), Year(bkObject.GetYear())
   {

   }

I changed the following for the assignment operator overloading
BookItem BookItem::operator=(const BookItem& temp)
   {

  if (this == &temp)
  {
  // IF THE RIGHT SIDE IS THE SAME AS THE LEFT SIDE
    return *this;
  }
    else
    {
    delete pub;
    Authors = temp.Authors;
    Title = temp.Title;
    pub = new Publisher(temp.pub->GetName());
    Year = temp.Year;

   return *this;
   } // end if

   }
Thanks for your help
Reply With Quote





Similar Threads
Thread Thread Starter Forum Replies Last Post
Constructors madhuriguda C# 2 April 29th, 2008 08:11 AM
Constructors - instantiation brysora C# 2005 1 September 3rd, 2007 08:45 PM
Cascading Constructors rodmcleay General .NET 4 May 18th, 2007 03:57 AM
Constructors return void? AndrewH Java Basics 4 February 13th, 2007 05:59 AM
Static Constructors Ibn_Aziz C# 3 December 25th, 2003 04:07 AM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.