-1

Simple.h

#pragma once
class Simple
{
public:
    Simple();
    void ShowIt();
};

**Simple.cpp**
#include "Simple.h"
#include <iostream>

Simple::Simple()
{
    std::cout << "in Simple Constructor" << std::endl;
}

void Simple::ShowIt()
{
    std::cout << "Showing It" << std::endl;
}

Main in file CppTutor2023.cpp:

#include "Simple.h"

int main()
{
   Simple obj1;
   Simple obj2();

   obj1.ShowIt();
   obj2.ShowIt();    // line 53
   ...

When I compile this I get the error:

Cpptutor2023.cpp(53,16): error C2228: left of '.ShowIt' must have class/struct/union

I expected line 52 to be the invalid one. Also what is difference between lines 49 & 50? Again, I expected compiler to complain about line 49.

I have Visual Studio options set to use C++ version 17.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
JCDeen
  • 139
  • 10
  • 5
    `Simple obj2();` is a function declaration. – Brian61354270 Jan 30 '23 at 01:32
  • 2
    [Is most vexing parse a formally defined concept](https://stackoverflow.com/questions/71937565/is-most-vexing-parse-a-formally-defined-concept) Why would you expect line 49 to be a problem? – Retired Ninja Jan 30 '23 at 01:34
  • 2
    `Simple obj2()` => `Simple obj2{}` – pm100 Jan 30 '23 at 01:35
  • 1
    Or `Simple obj2();` => `Simple obj2;` – Drew Dormann Jan 30 '23 at 01:38
  • 1
    Or if you want to get really fancy: `auto obj2 = Simple();` – Some programmer dude Jan 30 '23 at 01:47
  • 1
    Hint: look at the syntax coloring that was applied to your code automatically. Notice something different about the declarations of `obj1` and `obj2`? – Karl Knechtel Jan 30 '23 at 01:58
  • 1
    Look up "most vexing parse". The line `Simple obj2();` is interpreted as a declaration of a function named `obj2()` that accepts no arguments, and returns a `Simple`. So your subsequent usage of `obj2` is invalid - since your code does things that can't be done to a function. Options to fix include removing the `()` or (C++11 and later) changing the `()` to `{}` – Peter Jan 30 '23 at 01:58
  • 1
    "Again, I expected compiler to complain about line 49." **Why**? If you wrote `int x;`, would you be surprised that it worked, and wonder why you didn't have to write `int x();` instead? – Karl Knechtel Jan 30 '23 at 01:58

1 Answers1

2

This is a function declaration:

Simple obj2();

If the constructor takes no arguments, simply omit the ()

guard3
  • 823
  • 4
  • 13
  • Many thanks to everyone that answered! The comment about syntax coloring was a nice clue! Sure enough - I looked up my old code and was surprised to see that all my objects were instantiated exactly as you suggested. Guess I got wrapped around an axle a bit. Or I've been working with PHP way too long! :D – JCDeen Jan 30 '23 at 02:17