Sarti
Sarti

Reputation: 143

error: function was not declared in the scope

I have a class named logs_i with a virtual fucntion which named begin_record; I had to write a new class named counter_logs_t which supposed to has a method which counts the logs.

Here is the interface and the implemantation of counter_logs_t:

class counter_logs_t : public log_i
{
public:
    counter_logs_t(int counter);
    void print_counter(void);
    void add_counter(void);
    virtual void begin_record(void);

private:
    int counter;
};

counter_logs_t::counter_logs_t(int counter) : log_i()
{
    counter = 0;
}

void counter_logs_t::add_counter(void)
{
    counter++;
}

void logs_t::begin_record(void)
{
    log_i::begin_record();
    add_counter();
}


void counter_logs_t::print_counter(void){
    cout<< counter<< endl;
}

int main()
{

        counter_logs_t  container1();
//some code
        container1.print_counter();

    return 0;
}

When I try to build I got the following error: error: 'add_counter' was not declared in the scope

Upvotes: 0

Views: 801

Answers (3)

Cory Kramer
Cory Kramer

Reputation: 118001

The signature of this function is incorrect, specifically the class name

void logs_t::begin_record(void)

I think you meant

void counter_logs_t::begin_record(void)

Edit:

Your second issue is that you ran into the most vexing parse on this line

counter_logs_t  container1();

This is interpreted as declaring a function named container1 that takes no arguments and returns a coutner_logs_t. In fact, there is no default-constructor for counter_logs_t, the only constructor has the following signature

counter_logs_t(int counter);

Therefore you have to construct it with a counter argument.

counter_logs_t container1{0};
counter_logs_t container1 = counter_logs_t(0);

Or make a default constructor

counter_logs_t::counter_logs_t() : log_i(), counter(0) {}

then you can just say

counter_logs_t container1;

Upvotes: 1

XieYuan
XieYuan

Reputation: 1

void logs_t::begin_record(void)
{
    log_i::begin_record();
    add_counter();
}

in this function: 1. "logs_t" should be "counter_logs_t". 2. i don't recommend you to call class log_i's method begin_record() using "::" operator, unless you know it's a static method. You'd better call it like this this->begin_record for it's a virtual method.

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 181008

You also have an issue where

counter_logs_t container1();

Is not declaring a variable. It declares a function named container1 that reutrns a counter_logs_t and takes nothing. You need to change it to

counter_logs_t container1;

To declare a variable.

Upvotes: 1

Related Questions