Total members 9950 | Gratitudes |It is currently Sat Feb 11, 2012 2:11 am Login / Join Codemiles


All times are UTC [ DST ]




Post new topic Reply to topic  Quick reply  [ 1 post ] 
Author Question
 Question subject: Copy Constructor
PostPosted: Thu Nov 13, 2008 8:16 pm 
Offline
Beginner
User avatar

Joined: Sun May 25, 2008 5:34 pm
Posts: 95
Has thanked: 2 time
Have thanks: 1 time

here , A copy constructor to allow StringClass objects to be passed to functions
Code:
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class StringClass {
  char *p;
public:
  StringClass(char *s);           // constructor
  StringClass(const StringClass &o);  // copy constructor
  ~StringClass() {                // destructor
     delete [] p;
  }
  char *get() {
     return p;
  }
};


StringClass::StringClass(char *s)     // "Normal" constructor
{
  int l;

  l = strlen(s)+1;

  p = new char [l];
  if(!p) {
    cout << "Allocation error\n";
    exit(1);
  }

  strcpy(p, s);
}


StringClass::StringClass(const StringClass &o)   // Copy constructor
{
  int l;

  l = strlen(o.p)+1;

  p = new char [l];                  // allocate memory for new copy
  if(!p) {
    cout << "Allocation error\n";
    exit(1);
  }

  strcpy(p, o.p);                    // copy string into copy
}

void show(StringClass x)
{
  char *s;
   
  s = x.get();
  cout << s << endl;
}

int main()
{
  StringClass a("www.java2s.com"), b("www.java2s.com");

  show(a);
  show(b);

  return 0;
}


TOP
 Profile Send private message  
Reply with quote  
Post new topic Reply to topic Quick reply  [ 1 post ] 
Quick reply


  


 Similar topics
 Topic title   Forum   Author   Comments 
 Using a Constructor in jsp  JSP Examples  msi_333  2
 Java- Copy text area into disabled text area  Scripting Language  javahelpneeded  1
 copy file  ASP/ASP.net examples  msi_333  0
 copy folder  ASP/ASP.net examples  msi_333  0
 Easy Copy Paste Work From Home - Online Home Based Work  Job Opportunities  patelinfosoft196  0

All times are UTC [ DST ]


Users browsing similar posts

Users browsing this forum: No registered users and 2 guests



Jump to:  
Previous Question | Next Question 




Home
General Talks
Finished Projects
Code Library
Games
Tutorials

Java
C/C++
C-sharp
php
Script
JSP/Servlets
Ajax
ASP/ASP.net
Google SEO
Database
Communications
Phpbb3 styles
Photoshop tutorials
Flash tutorials
Find a job






Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group
All copyrights reserved to codemiles.com 2007-2011
mileX v1.0 designed by codemiles team