Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Can someone help me to make code

–2 votes
asked Nov 16, 2020 by Amina Slabic (160 points)
I did a lot of work and its easy program, but idk how to put more than 2 methds in one class, c++. If i tried something from internet it just doesnt want to work. so if someone can help me ty

1 Answer

+2 votes
answered Nov 18, 2020 by Peter Minarik (55,660 points)
edited Nov 18, 2020 by Peter Minarik

Share your code

Please, share your code so we can see what you did and find out what the mistake was there. This way you can get personalised answer to your question.

Examples

I can provide some silly examples, maybe they help too.

Simple class:

#include <iostream>

class Dog
{
public:
    void Bark()
    {
        std::cout << "Woof, woof" << std::endl;
    }
    
    void Eat()
    {
        std::cout << "Yum, yum" << std::endl;
    }
};

int main()
{
    Dog dog;
    dog.Bark();
    dog.Eat();

    return 0;
}

Class separated to header and source file:

You can download the sample project from here. Please note that functions marked as const can not change the state of the class (right now the only "state" is the _name). If you want to change the class itself in the method, do not mark those method as const.

dog.h

#pragma once

#include <string>

class Dog
{
private:
    std::string _name;

public:
    Dog(std::string name);
    void Bark() const;
    void Eat(const std::string & food) const;
};

dog.cpp

#include "Dog.h"

#include <iostream>

Dog::Dog(std::string name) : _name(name) { }

void Dog::Bark() const
{
    std::cout << _name << " barks: Woof-woof" << std::endl;
}

void Dog::Eat(const std::string & food) const
{
    std::cout << _name << " eats " << food << ": Yum-yum" << std::endl;
}

main.cpp

#include "Dog.h"

int main()
{
    Dog dog("Butch");
    dog.Bark();
    dog.Eat("steak");

    return 0;
}

Sample execution:

Butch barks: Woof-woof
Butch eats steak: Yum-yum
commented Dec 21, 2020 by Amina Slabic (160 points)
Tysm i forgot that i asked here lmao. But ty anyway
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...