Using Variables in Classes

closed account (9G3v5Di1)
The error says error: invalid conversion from 'const char*' to 'char' [-fpermissive]
bryansObject.setName("bryan");


and

note: initializing argument 1 of 'void BryansClass::setName(char)'
void setName(char x){
^~~~~~~


However, the codes came from a tutorial in youtube named thenewboston. It perfectly works in the tutorial video but when I copied it, something went wrong. The codes are to print name.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
  #include <stdio.h>
#include <iostream>
#include <string>
#include "_pause.h"

using namespace std;

class BryansClass{
	public:
		void setName(char x){
			name = x;
		}
		char getName(){
			return name;
		}
	private:
	char name;
};

int main(){
	BryansClass bryansObject;
	bryansObject.setName("bryan");

	cout << bryansObject.getName();

	std:cin.get();
	_pause();
	return EXIT_SUCCESS;
}


Edited: the data type "char" was written as 'string' in the tutorial. The tutorial video was 7 years ago.
Last edited on
Take a close look at my example and you will see why yours doesn't work. ;-)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <string>
#include <iostream>

class Person
{
   public:
	  void setName(std::string nameVal)
	  {
		 name = nameVal;
	  }

	  const std::string getName() const
	  {
		 return name;
	  }

   private:
	  std::string name;
};

auto main() -> int
{
   Person pOne;
   pOne.setName("Miuna Takahata");
   std::cout << pOne.getName() << std::endl;

   return 0;
}
closed account (9G3v5Di1)
wow. But as what my friend told me, string was used before c++ was updated recently and string was changed into char. String doesn't accept spaces(space bar) because it always causes error so it was only designed for just a word (string = 1 word).

how is this possible
as what my friend told me, string was used before c++ was updated recently and string was changed into char
Your friend is mistaken. Strings can hold any sequence of characters. As for spaces, your friend is probably confusing what a string can hold vs. what operator>>(istream&, string &) will do:
1
2
string str;
cin >> str;  // operator reads one word into str 

You can also read a whole line into a string with getline()
Topic archived. No new replies allowed.