Overloading assignment operator with Classes and Vectors - c++

I have a class defined:
#ifndef _STRINGCLASS_H
#define _STRINGCLASS_H
using namespace std;
#include <iostream>
#include <vector>
class String {
protected:
int length;
vector<string> buf;
public:
String();
String(const char* input);
String(char input);
String(int input);
String(const String& input);
String(char input, int input2);
String& operator=(const String& input);
};
#endif
and am trying to overload the assignment operator by such:
String& operator=(const String& input) {
buf = input.buf;
length = input.length;
return *this;
}
and I get the error code that buf is protected and length is protected. I'm not sure what I am missing. How can I properly overload the assignment operator with vectors and ints?

You do not need to provide any special member functions for your class, because the compiler synthesized ones will do the right thing in this case. The best option is to remove the assignment operator and copy constructor from your class definition.
class String
{
protected:
int length;
vector<string> buf;
public:
String();
String(const char* input);
String(char input);
String(int input);
String(char input, int input2);
};

You need to define the implementation as part of the class. You are missing the class specifier:
// vvvvvvvv
String& String::operator=(const String& input) {
buf = input.buf;
length = input.length;
return *this;
}
As written, you are defining a free operator overload (not bound to a class), and it's actually invalid to declare a free assignment operator overload anyway.
From the perspective of a free operator overload that isn't a member of String, buf and length are indeed inaccessible because they are private.

Related

C++ code to overload the assignment operator does not work

I'm having some issues compiling the code I wrote which has a custom class with an overloaded =.
rnumber.hpp:
#include <string>
class rnumber {
public:
std::string number;
// I added this constructor in an edit
rnumber(std::string s) { number = s; }
void operator=(std::string s) { number = s; }
bool operator==(std::string s) { return number == s; }
friend std::ostream &operator<<(std::ostream &os, const rnumber n);
};
std::ostream &operator<<(std::ostream &os, const rnumber n) {
os << n.number;
return os;
}
main.cpp:
#include "rnumber.hpp"
#include <iostream>
#include <string>
int main() {
rnumber a = "123";
}
For some reason, this does not compile with the error conversion from ‘const char [4]’ to non-scalar type ‘rnumber’ requested. This shouldn't be a problem, because rnumber has an overload for =. Why am I getting this error?
EDIT: Even after adding a constructor, it doesn't work.
rnumber a = "123"; tries to initialize a with a const char*, but there is no constructor taking a const char*.
You need to implement this constructor as well:
rnumber(const char *s) { number = s; }
There are other possibilities, mentioned on other answer and comments.
The problem is that rnumber a = "123"; is initialization and not assignment so that the copy assignment operator= cannot be used.
There are 2 ways to solve this as shown below:
Method 1
Use the converting constructor rnumber::rnumber(std::string)
int main() {
rnumber a("123"); //this uses the converting ctor
}
Method 2
Create the object and then do the assignment:
int main() {
rnumber a("somestring"); //creates the object using converting ctor
a = "123"; //uses assignment operator
}
"abc" is not a std::string literal, it is a string literal, in particular it is a const char[4]. There is an implicit conversion from const char[4] to std::string, by one of it's constructors, and an implicit conversion from std::string to rnumber by the constructor you edited in, but you only get one implicit constructor per initialisation.
What you can do is explicitly construct the rnumber, and the std::string parameter can be implicitly constructed.
int main() {
rnumber a { "123" };
}
The problem's that I was using the wrong constructor.
rnumber(std::string s) { number = s; } is an std::string constructor, where the assignment rnumber a = "123"; is assigning a const char* to a.
Add another constructor rnumber(const char *s) { number = s; } to the header.

strcpy not working with string pointer in a class

I'm new to c++.I made a simple program that name members of class based on your input.
But for some reason, compiler shows this error - 'str': is not a member of 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>', I have trouble understanding what it means.
Please help me out
here is my code -
#include <iostream>
#include <string>
#include <vector>
class mystring
{
private:
std::string *str;
public:
//constructors
mystring();
mystring(const std::string &strthing);
~mystring();
//methods
void display() const;
};
mystring::mystring() //defalt constructor
:str(nullptr)
{}
mystring::mystring(const std::string& strthing) //copy constructor
:str(nullptr)
{
delete str;
str = new std::string;
strcpy(this->str, strthing.str);
std::cout << "overloaded\n";
}
mystring::~mystring() //destructor
{
delete [] str;
}
void mystring::display() const //display func
{
std::cout << *str;
}
int main()
{
mystring thing;
mystring object{ "samurai" };
object.display();
}
I think something is wrong with the strcpy() function in overloaded constructor.
Thanks
There is nothing wrong with strcpy, but with how you use it. std::strings can be copied with their operator=:
std::string a;
std::string b;
a = b; // copy b to a
strcpy on the other hand is for c-strings, which a std::string is not:
char* strcpy( char* dest, const char* src );
It is unclear why you have a member of type pointer to std::string. You should either use a std::string (no pointer), or if this is an exercise to write your own string class (not an easy one!) then you should probably store the data in an array of chars.
The error you get is about strthing.str. Here strthing is a std::string which has no str member. If that constructor is supposed to be a copy constructor it should take a const mystring& as parameter not a const std::string&.
This is just a typo.
mystring::mystring(const std::string& strthing)
Should be
mystring::mystring(const mystring& strthing)
You don't use strcpy to copy std::string objects. Here's your constructor rewritten correctly (it's not a copy constructor because it doesn't copy mystring objects)
mystring::mystring(const std::string& strthing) // constructor from std::string
: str(new std::string(strthing)) // allocate new string by copying from strthing
{
std::cout << "overloaded\n";
}
Because your class allocates memory (not sure why it does but it does) you do actually need to write a genuine copy constructor and assignment operator
mystring::mystring(const mystring& strthing) // copy constructor
mystring& mystring::operator=(const mystring& strthing) // assignment operator
But I'll leave that to you.
Ther is a C++ trap between C++ type std::string and C type 'char*'.
std::string can convert to char* using std::string.c_str().
And strcpy takes char* and char const * as parameters.
In moderen C++ practice, use std::string usually, std::string * is not recommended to use.
If you want to use strcpy with std::string, you have to do the conversion between char * and std::string. Below is a simple Example:
std::string dest;
std::string source = "Hello, World!";
char temp[40];
strcpy(temp, source.c_str());
dest = temp;

overload array operator for mystring class

I need help figuring out how to overload the array operator for a MyString class that I have to create. I already have everything else figured out, but the arrays are giving me trouble, for some reason.
Here is my header file:
#ifndef MYSTRING_H
#define MYSTRING_H
#include <iostream>
#include <cstring> // For string library functions
#include <cstdlib> // For exit() function
using namespace std;
// MyString class: An abstract data type for handling strings
class MyString
{
private:
char *str;
int len;
public:
// Default constructor.
MyString()
{
str = 0;
len = 0;
}
// Convert and copy constructors.
MyString(char *);
MyString(MyString &);
// Destructor.
~MyString()
{
if (len != 0)
delete [] str;
str = 0;
len = 0;
}
// Various member functions and operators.
int length() { return len; }
char *getValue() { return str; };
MyString operator+=(MyString &);
MyString operator+=(const char *);
MyString operator=(MyString &);
MyString operator=(const char *);
bool operator==(MyString &);
bool operator==(const char *);
bool operator!=(MyString &);
bool operator!=(const char *);
bool operator>(MyString &);
bool operator>(const char *);
bool operator<(MyString &);
bool operator<(const char *);
bool operator>=(MyString &);
bool operator>=(const char*);
bool operator<=(MyString &);
bool operator<=(const char *);
MyString operator [](MyString *);
// Overload insertion and extraction operators.
friend ostream &operator<<(ostream &, MyString &);
friend istream &operator>>(istream &, MyString &);
};
#endif
What would the body look like for MyString::operator []?
MyString MyString::operator [](MyString *)
{
... what goes here
}
The syntax for using the array operator with an object of the given class is:
MyString s("Test");
char c = s[0];
The argument to the function is an integral value.
Hence, the operator needs to be declared as:
// The non-const version allows you to change the
// content using the array operator.
char& operator [](size_t index);
// The nconst version allows you to just get the
// content using the array operator.
char operator [](size_t index) const;
MyString MyString::operator [](MyString *)
That's not how you should typically use a subscript operator.
What do you expect when you are using the [] operator? By the way you declared it, you are using a string pointer as argument, and receiving a string as return.
Usually, you pass an index type (commonly an unsigned-integer like size_t) and return the character at that position. If that's what you want, you should do something along these lines:
char& MyString::operator [](size_t position)
{
// some error handling
return str[position];
}
char MyString::operator [](size_t position) const { /* ... */ }
For overall guidelines on overloading operators, take a look at What are the basic rules and idioms for operator overloading?.
Also, I would point out that your destructor is a bit odd:
if (len != 0)
delete [] str;
str = 0;
len = 0;
Your indentation level suggests that you expect everything to happen inside the if statement, but only the first one will. That is not particularly dangerous in this case, because only the delete would suffice.
There is no problem in deleteing a null pointer, and str and len will be destroyed shortly after, so you don't have to bother resetting them.

declaration is incompatible, beginner c++

I just need a little help on this assignment. I have to redefine operators to work with strings. I'm starting with the == operator and I have it declared in my header file, however when I go to define the function in my cpp file, it says it's incompatible with the declared function. It's probably a stupid mistake, I just don't understand this sometimes.
string.h header file
#pragma once
#include <iostream>
#include <string>
using namespace std;
#define NOT_FOUND -1
// C++ String class that encapsulates an ASCII C-string
class String
{
public:
// Default constructor
String();
// MUST HAVE: Copy-constructor that performs deep copy
String(const String& source);
// Init-constructor to initialize this String with a C-string
String(const char* text);
// Init constructor, allocates this String to hold the size characters
String(int size);
// Destructor
~String();
bool& compareTo(const String& cmp1);
// Assignment operator to perform deep copy
String& operator = (const String& source);
// Assignment operator to assign a C-string to this String
String& operator = (const char* text);
// Returns a reference to a single character from this String
char& operator [] (int index) const;
// Comparison operators
bool operator == (const String& compareTo) const;
string.cpp file
#include "string.h"
#include <string>
#include <sstream>
using namespace std;
// Default constructor
String::String()
{
Text = NULL;
}
// MUST HAVE: Copy-constructor that performs deep copy
String::String(const String& source)
{
Text = NULL;
// Call the assignment operator to perform deep copy
*this = source;
}
// Init-constructor to initialize this String with a C-string
String::String(const char* text)
{
Text = NULL;
// Call the assignment operator to perform deep copy
*this = text;
}
// Init constructor, allocates this String to hold the size characters
String::String(int size)
{
Text = new char[size];
}
// Destructor
String::~String()
{
delete[] Text;
}
// Assignment operator to perform deep copy
String& String::operator = (const String& source)
{
// Call the other assigment operator to perform deep copy
*this = source.Text;
return *this;
}
// Assignment operator to assign a C-string to this String
String& String::operator = (const char* text)
{
// Ddispose of old Text
delete[] Text;
// +1 accounts for NULL-terminator
int trueLength = GetLength(text) + 1;
// Dynamically allocate characters on heap
Text = new char[trueLength];
// Copy all characters from source to Text; +1 accounts for NULL-terminator
for ( int i = 0; i < trueLength; i++ )
Text[i] = text[i];
return *this;
}
***bool& String::operator ==(string cmp2)***
{
};
Your compareTo declaration has const while definition has no const, which means they have definition has different signature with declaration:
bool& compareTo(const String& cmp1);
^^^
bool& String::compareTo(string cmp2)
{
};
BTW, why does your compareTo return bool& ?
Also should avoid using namespace std; in any header files. see why-is-using-namespace-std-considered-a-bad-practice-in-c

error: expected ')' before '<' token|

I was implementing a String and was giving the definition in .h file. The code in String.h is the following:
#include<list>
class String
{
public:
String();//Constructor
String(char * copy);//For converting CString to String
const char *c_str(const String &copy);//For converting String to Cstring
String(list<char> &copy);//Copying chars from list
//Safety members
~String();
String(const String &copy);
void operator = (const String &copy);
protected:
int length;
char *entries;
};
The error is mentioned in the subject. What is it that I am not following?
You are missing a std:: in front of list<char> :
String(std::list<char> &copy);
Fixed several of your issues at once:
#include <list>
class String
{
public:
String();
String(const String &c);
String(const char * c);
String(std::list<char> c); // No idea why someone would have this constructor, but it was included in the original ...
~String();
String& operator = (const String &c);
const char *c_str();
private:
unsigned int length;
char* entries;
};