How to create object of class using char variable

class Test {}


char const * objectName = "Test";
Test("objectName");

Please advise
Can you add a little bit more explanation? Your variable is called objectName but you are passing the string literal "objectName". Is that intentional? Or are you just trying to pass "Test" as a parameter into your class constructor?

Assuming the latter...

Constructor example that uses strings:
https://www.w3schools.com/cpp/cpp_constructors.asp
(w3school's tutorial makes a minor wrong point; a constructor is not necessarily public, but for your purposes it will be.)

https://www.learncpp.com/cpp-tutorial/constructors/
Last edited on
Test myTestVariable(objectName); //notice the lack of quotes on objectName.
creates a new variable of type Test
which is named myTestVariable
and has been initialized/constructed with your const char* data.

this is syntax identical to
int myInt(42);
(integers are not objects, exactly, but the syntax mirrors)


in the very odd case that Test was designed to allow it,
Test(objectName); //this could do something, if you wrote it that way, but this is an advance form of using special purpose objects that I suspect you were not trying to do.
Last edited on
How to create object of class using char variable


Do you mean something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <string>
#include <iostream>

class Test {
	std::string s;

public:
	Test(const char* st) : s(st) {}

	void display() const {
		std::cout << s << '\n';
	}
};

int main() {
	Test t { "foobar" };

	t.display();
}

I need to create object using char * or string;
then I want to create object of class Test testObj;
how to put testObj from variable?
Based on seeplus's code:
1
2
const char* str = "foobar";
Test testObj(str);
Last edited on
If you want to use strings to refer to objects you can use std::map (or std::unordered_map).

 
std::map<std::string, Test> myTestObjects;

You can then use myTestObjects[str] to access the object referred to by the string str (if there is no such object it will be created automatically).
Last edited on
Topic archived. No new replies allowed.