C++ Error: conversion to non-scalar type requested?

21,899
FlexString flex_str = new FlexString();

is wrong since the RHS of the assignment is a pointer to a FlexString while the LHS is an object.

You can use:

// Use the default constructor to construct an object using memory
// from the stack.
FlexString flex_str;

or

// Use the default constructor to construct an object using memory
// from the free store.
FlexString* flex_str = new FlexString();
Share:
21,899
camohreally
Author by

camohreally

Updated on July 05, 2022

Comments

  • camohreally
    camohreally almost 2 years

    I'm fairly new to C++ and i'm trying to build a linked list with a container class called FlexString. In main() I want to instantiate the FlexString class by simply saying: "FlexString flex_str = new FlexString();" calling the constructor etc. But it won't compile, the error is at the bottom. Here is my code:

        //FlexString.h file
    #ifndef FLEXSTRING_CAMERON_H
    #define FLEXSTRING_CAMERON_H
    #include "LinkedList.h"
    #include <string>
    
    using namespace std;
    using oreilly_A1::LinkedList;
    
    namespace oreilly_A1 {
    class FlexString {
    public:
    
        FlexString();
        void store(std::string& s);
        size_t length();
        bool empty();
        std::string value();
        size_t count();
    
    
    
    
    private:
    
        LinkedList data_list;
    
    };
    }
    #endif
    

    Here is the .cpp file for the FlexString class:

    #include "FlexString.h"
    #include "LinkedList.h"
    #include <string>
    
    using namespace std;
    
    namespace oreilly_A1 {
        FlexString::FlexString() {
    
        }
    
        void FlexString::store(string& s) {
            data_list.list_head_insert(s);
        }
    
        std::string value() {
            data_list.list_getstring(); 
        }
    
    }
    

    Here's the main program file.

    #include <iostream>
    #include <cstdlib>
    #include "FlexString.h"
    
    using namespace std;
    using oreilly_A1::FlexString;
    
    int main() {
    
        FlexString flex_str = new FlexString();
        cout << "Please enter a word: " << endl;
        string new_string;
        cin >> new_string;
    
        flex_str.store(new_string);
    
        cout << "The word you stored was: "+ flex_str.value() << endl;
    
    }
    

    error: conversion from 'oreilly_A1::FlexString*' to non-scalar type 'oreilly_A1::FlexString' requested. "FlexString flex_str = new FlexString();"