C++ program to overload operator+ for string concatenation

//operator overloading for concatenating two strings in C++
#include<iostream>
using namespace std;
#include<string.h>

class sample
{
private:
char str[20];
public:
sample()
{
cout<<"def constructor."<<endl;
strcpy(str,"C++ Linux Code.");
}
sample(char s[])
{
cout<<"a arg constructor."<<endl;
strcpy(str,s);
}
sample operator+(const sample& ref )
{
cout<<"overloaded + called"<<endl;
sample temp;//def constructor
strcpy(temp.str,str);
strcat(temp.str,ref.str);
return temp;
}
//return *this;//seg fault
void display(){cout<<str<<endl;}
};
int main()
{
sample s1;//def constructor
s1.display();
sample s2("blogspot.com");//1 arg constructor
s2.display();
sample s3;//def constructor
s3=s1+s2;
s3.display();
//cout<<str<<endl;//str was not declared in this scope. As str is private and only mf can access
//cout<<s1.str<<endl;//aaa
//cout<<'m'<<endl;//a
return 0;
}
/*
def constructor.
C++ Linux Code.
a arg constructor.
blogspot.com
def constructor.
overloaded + called
def constructor.
C++ Linux Code.blogs
*/

2 comments:

  1. //operator overloading for concatenating two strings in C++
    #include
    using namespace std;
    #include

    class sample
    {
    private:
    char str[20];
    public:
    sample()
    {
    cout<<"def constructor."<<endl;
    strcpy(str,"C++ Linux Code.");
    }
    sample(char s[])
    {
    cout<<"a arg constructor."<<endl;
    strcpy(str,s);
    }
    sample operator+(const sample& ref )
    {
    cout<<"overloaded + called"<<endl;
    sample temp;//def constructor
    strcpy(temp.str,str);
    if(strlen(temp.str)+strlen(ref.str)<20)
    {
    strcat(temp.str,ref.str);
    return temp;
    }
    else
    {
    cout<<"concatenated string is larger"<<endl;
    temp=0;
    return temp;
    }
    return temp;
    //return *this;//seg fault
    }
    void display(){cout<<str<<endl;}
    };
    int main()
    {
    sample s1;//def constructor
    s1.display();
    sample s2("blogspot.com");//1 arg constructor
    s2.display();
    sample s3;//def constructor
    s3=s1+s2;
    s3.display();
    //cout<<str<<endl;//str was not declared in this scope. As str is private and only mf can access
    //cout<<s1.str<<endl;//aaa
    //cout<<'m'<<endl;//a
    return 0;
    }

    ReplyDelete
  2. Lmao c is getting on my nerves

    ReplyDelete