dcsimg
Results 1 to 3 of 3

Thread: Define the name of an object in a class based on a string value in C++

  1. #1

    Thread Starter
    Lively Member Mr. G's Avatar
    Join Date
    Dec 2006
    Location
    Sweden
    Posts
    107

    Define the name of an object in a class based on a string value in C++

    I have a class as stated below. What I want to do is to assign the class a value based on a string value (the string is called sObject), like below. How do I do that?

    Code:
    #include <iostream>
    #include <fstream> //for reading csv file I believe
    #include <bits/stdc++.h> //for classes
    
    using namespace std;
    
    class Category
    {
    	// Access specifier
    	public:
    
    	// Data Members
    	string sCategory;
    
    	// Member Functions()
    	void printname(){
            cout << "Category is: " << sCategory;
    	}
    };
    
    
    int main(){
    
           string sObject
            sObject= "BMW"
    
    	// Declare an object of class
    	Category sObject;
    
    	// accessing data member
    	sObject.sCategory = "3 series";
    
    	// accessing member function
    	sObject.printname();
    
    }

  2. #2
    Fanatic Member 2kaud's Avatar
    Join Date
    May 2014
    Location
    England
    Posts
    632

    Re: Define the name of an object in a class based on a string value in C++

    In c++ classes and class instances do not have 'a value'. The class member variables for each object instance of a class contain data for that instance. So in this case, sObject is a class instance of Category and has it's sCategory member variable set to 3 series. However the proceeding attempt to assign the value BMW to sObject is invalid as sObject itself cannot have a value. The make either needs to be stored as another member of Category, or you could create another class called something like Manufacturer (which has a member variable to hold the manufacturer's name) and derive class Category from that.

    Depending upon what you are trying to do, a multi-map may be better.
    All advice is offered in good faith only. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/

    C++17 Compiler: Microsoft VS2019 (16.3.5)

  3. #3

    Thread Starter
    Lively Member Mr. G's Avatar
    Join Date
    Dec 2006
    Location
    Sweden
    Posts
    107

    Re: Define the name of an object in a class based on a string value in C++

    Ok, thanks. I'll try a map instead!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width