Thread: Help me with function call

  1. #1
    Registered User
    Join Date
    May 2008
    Posts
    52

    Help me with function call

    I have 2 files, one is mainwindow.cpp and the other is mega.cpp


    In mega.cpp i call a function Void that is defined in mainwindow.cpp, like this:

    MainWindow::newIdentity();

    But i get this error:

    error: cannot call member function `void MainWindow::newIdentity()' without obj
    ect

  2. #2
    Registered User
    Join Date
    May 2008
    Posts
    52
    In mainwindow.cpp the function is defined like this:


    Code:
    void MainWindow::newIdentity()
    { .... }

  3. #3
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Post your code and how you are trying to build it. You also should invest in a good C++ book.

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by NeMewSys View Post
    I have 2 files, one is mainwindow.cpp and the other is mega.cpp


    In mega.cpp i call a function Void that is defined in mainwindow.cpp, like this:

    MainWindow::newIdentity();

    But i get this error:

    error: cannot call member function `void MainWindow::newIdentity()' without obj
    ect
    Correct. If you want to call newIdentity without an object instance, then newIdentity needs to be a static function. As medievalelks says, it would help a lot of you post a bit more code, so that we can see the context of the problem.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    You need

    MainWindow myWindow; // an instance of your class.

    Then later
    myWindow.newIdentity(); // call the function, using myWindow as the object.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    The class is a blueprint, you must create something from it first (you can't hit the gas pedal in a car from a car blueprint--you must hit it inside an actual car).
    Last edited by Elysia; 05-21-2008 at 10:41 AM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    3735928559
    Join Date
    Mar 2008
    Location
    RTP
    Posts
    838
    that's an odd, but apt, analogy.

  8. #8
    Registered User
    Join Date
    May 2008
    Posts
    52
    The code comes from vidalia's source:

    the mainwindow.cpp:
    Code:
    /*
    **  This file is part of Vidalia, and is subject to the license terms in the
    **  LICENSE file, found in the top level directory of this distribution. If you
    **  did not receive the LICENSE file with this file, you may obtain it from the
    **  Vidalia source package distributed by the Vidalia Project at
    **  http://www.vidalia-project.net/. No part of Vidalia, including this file,
    **  may be copied, modified, propagated, or distributed except according to the
    **  terms described in the LICENSE file.
    */
    
    /*
    ** \file mainwindow.cpp
    ** \version $Id: mainwindow.cpp 2362 2008-02-29 04:30:11Z edmanm $
    ** \brief Main (hidden) window. Creates tray menu and child windows
    **
    ** Implements the main window. The main window is a hidden window that serves
    ** as the parent of the tray icon and popup menu, as well as other application
    ** dialogs.
    */
    
    #include <QtGui>
    #include <QTimer>
    #include <vidalia.h>
    #include <file.h>
    #include <html.h>
    #include <stringutil.h>
    #include <net.h>
    #include <clientstatusevent.h>
    #include <dangerousversionevent.h>
    #include <vmessagebox.h>
    #include "config.h"
    
    #include "mainwindow.h"
    
    
    #define IMG_BWGRAPH        ":/images/16x16/utilities-system-monitor.png"
    #define IMG_CONTROL_PANEL  ":/images/16x16/preferences-desktop.png"
    #define IMG_MESSAGELOG     ":/images/16x16/format-justify-fill.png"
    #define IMG_CONFIG         ":/images/16x16/preferences-system.png"
    #define IMG_IDENTITY       ":/images/16x16/system-users.png"
    #define IMG_HELP           ":/images/16x16/help-browser.png"
    #define IMG_ABOUT          ":/images/16x16/tor-logo.png"
    #define IMG_EXIT           ":/images/16x16/emblem-unreadable.png"
    #define IMG_NETWORK        ":/images/16x16/applications-internet.png"
    
    #define IMG_START_TOR_16     ":/images/16x16/start-tor.png"
    #define IMG_STOP_TOR_16      ":/images/16x16/stop-tor.png"
    #define IMG_START_TOR_48     ":/images/48x48/start-tor.png"
    #define IMG_STOP_TOR_48      ":/images/48x48/stop-tor.png"
    #define IMG_TOR_STOPPED_48   ":/images/48x48/tor-off.png"
    #define IMG_TOR_RUNNING_48   ":/images/48x48/tor-on.png"
    #define IMG_TOR_STARTING_48  ":/images/48x48/tor-starting.png"
    #define IMG_TOR_STOPPING_48  ":/images/48x48/tor-stopping.png"
    
    #define ANIM_PROCESS_WORKING  ":/images/32x32/process-working.png"
    
    /* Decide which of our four sets of tray icons to use. */
    #if defined(Q_WS_WIN)
    /* QSystemTrayIcon on Windows wants 16x16 .png files */
    #define IMG_TOR_STOPPED  ":/images/16x16/tor-off.png"
    #define IMG_TOR_RUNNING  ":/images/16x16/tor-on.png"
    #define IMG_TOR_STARTING ":/images/16x16/tor-starting.png"
    #define IMG_TOR_STOPPING ":/images/16x16/tor-stopping.png"
    #elif defined(Q_WS_MAC)
    /* On Mac, we always go straight to Carbon to load our dock images 
     * from .icns files */
    #define IMG_TOR_STOPPED    "tor-off"
    #define IMG_TOR_RUNNING    "tor-on"
    #define IMG_TOR_STARTING   "tor-starting"
    #define IMG_TOR_STOPPING   "tor-stopping"
    #else
    /* On X11, we just use always the 22x22 .png files */
    #define IMG_TOR_STOPPED    ":/images/22x22/tor-off.png"
    #define IMG_TOR_RUNNING    ":/images/22x22/tor-on.png"
    #define IMG_TOR_STARTING   ":/images/22x22/tor-starting.png"
    #define IMG_TOR_STOPPING   ":/images/22x22/tor-stopping.png"
    #endif
    
    /** Only allow 'New Identity' to be clicked once every 10 seconds. */
    #define MIN_NEWIDENTITY_INTERVAL   (10*1000)
    
    
    /** Default constructor. It installs an icon in the system tray area and
     * creates the popup menu associated with that icon. */
    MainWindow::MainWindow()
    : VidaliaWindow("MainWindow")
    {
      VidaliaSettings settings;
    
      ui.setupUi(this);
    
      /* Create all the dialogs of which we only want one instance */
      _messageLog     = new MessageLog();
      _bandwidthGraph = new BandwidthGraph();
      _netViewer      = new NetViewer();
      _configDialog   = new ConfigDialog();
      connect(_messageLog, SIGNAL(helpRequested(QString)),
              this, SLOT(showHelpDialog(QString)));
      connect(_netViewer, SIGNAL(helpRequested(QString)),
              this, SLOT(showHelpDialog(QString)));
      connect(_configDialog, SIGNAL(helpRequested(QString)),
              this, SLOT(showHelpDialog(QString)));
    
      /* Create the actions that will go in the tray menu */
      createActions();
      /* Creates a tray icon with a context menu and adds it to the system's
       * notification area. */
      createTrayIcon();
      /* Start with Tor initially stopped */
      _status = Unset;
      updateTorStatus(Stopped);
      
      /* Create a new TorControl object, used to communicate with Tor */
      _torControl = Vidalia::torControl(); 
      connect(_torControl, SIGNAL(started()), this, SLOT(started()));
      connect(_torControl, SIGNAL(startFailed(QString)),
                     this,   SLOT(startFailed(QString)));
      connect(_torControl, SIGNAL(stopped(int, QProcess::ExitStatus)),
                     this,   SLOT(stopped(int, QProcess::ExitStatus)));
      connect(_torControl, SIGNAL(connected()), this, SLOT(connected()));
      connect(_torControl, SIGNAL(disconnected()), this, SLOT(disconnected()));
      connect(_torControl, SIGNAL(connectFailed(QString)), 
                     this,   SLOT(connectFailed(QString)));
      connect(_torControl, SIGNAL(authenticated()), this, SLOT(authenticated()));
      connect(_torControl, SIGNAL(authenticationFailed(QString)),
                     this,   SLOT(authenticationFailed(QString)));
      _torControl->setEvent(TorEvents::ClientStatus,  this, true);
      _torControl->setEvent(TorEvents::GeneralStatus, this, true);
    
      /* Create a new HelperProcess object, used to start the web browser */
      _browserProcess = new HelperProcess(this);
      connect(_browserProcess, SIGNAL(finished(int, QProcess::ExitStatus)),
               this, SLOT(onBrowserFinished(int, QProcess::ExitStatus)));
      connect(_browserProcess, SIGNAL(startFailed(QString)),
               this, SLOT(onBrowserFailed(QString)));
    
      /* Create a new HelperProcess object, used to start the proxy server */
      _proxyProcess = new HelperProcess(this);
      connect(_proxyProcess, SIGNAL(startFailed(QString)),
               this, SLOT(onProxyFailed(QString)));
    
      /* Catch signals when the application is running or shutting down */
      connect(vApp, SIGNAL(running()), this, SLOT(running()));
      connect(vApp, SIGNAL(shutdown()), this, SLOT(shutdown()));
     
      if (TrayIcon::isTrayIconSupported()) {
        /* Make the tray icon visible */
        _trayIcon.show();
        /* Check if we are supposed to show our main window on startup */
        ui.chkShowOnStartup->setChecked(settings.showMainWindowAtStart());
        if (ui.chkShowOnStartup->isChecked())
          show();
      } else {
        /* Don't let people hide the main window, since that's all they have. */
        ui.chkShowOnStartup->hide();
        ui.btnHide->hide();
        setMinimumHeight(height()-ui.btnHide->height());
        setMaximumHeight(height()-ui.btnHide->height());
        show();
      }
    }
    
    /** Destructor. */
    MainWindow::~MainWindow()
    {
      _trayIcon.hide();
      delete _messageLog;
      delete _bandwidthGraph;
      delete _netViewer;
      delete _configDialog;
    }
    
    
    
    .........
    ........
    ........
    ........
    .........
    
    
    /** Called when the user selects the "New Identity" action from the menu. */
    void
    MainWindow::newIdentity()
    {
      QString errmsg;
    	//SetInterval(MainWindow::newIdentity,60*1000);
      /* Send the NEWNYM signal. If message balloons are supported and the NEWNYM
       * is successful, we will show the result as a balloon. Otherwise, we'll 
       * just use a message box. */
      if (_torControl->signal(TorSignal::NewNym, &errmsg)) {
        /* NEWNYM signal was successful */
        QString title = tr("New Identity");
        QString message = tr("Proeza das bananas!");
    
        /* Disable the New Identity button for MIN_NEWIDENTITY_INTERVAL */
        _newIdentityAct->setEnabled(false);
        ui.lblNewIdentity->setEnabled(false);
        QTimer::singleShot(MIN_NEWIDENTITY_INTERVAL, 
                           this, SLOT(enableNewIdentity()));
    
        if (TrayIcon::supportsBalloonMessages())
          _trayIcon.showBalloonMessage(title, message, TrayIcon::Information);
        else
          VMessageBox::information(this, title, message, VMessageBox::Ok);
      } else {
        /* NEWNYM signal failed */
        VMessageBox::warning(this, 
          tr("Failed to Create New Identity"), errmsg, VMessageBox::Ok);
      }
    }
    
    /** Re-enables the 'New Identity' button after a delay from the previous time
     * 'New Identity' was used. */
    void
    MainWindow::enableNewIdentity()
    {
      if (_torControl->isConnected()) {
        _newIdentityAct->setEnabled(true);
        ui.lblNewIdentity->setEnabled(true);
      }
    }
    
    /** Converts a TorStatus enum value to a string for debug logging purposes. */
    QString
    MainWindow::toString(TorStatus status)
    {
      switch (status) {
        /* These strings only appear in debug logs, so they should not be
         * translated. */
        case Unset:     return "Unset";
        case Stopping:  return "Stopping";
        case Stopped:   return "Stopped";
        case Starting:  return "Starting";
        case Started:   return "Started";
        case Authenticating:  return "Authenticating";
        case Authenticated:   return "Authenticated";
        case CircuitEstablished: return "Circuit Established";
        default: break;
      }
      return "Unknown";
    }
    
    
    ///EOF

    my file's code (where i want to call MainWindow::newIdentity()):
    Code:
    /*
    **  This file is part of Vidalia, and is subject to the license terms in the
    **  LICENSE file, found in the top level directory of this distribution. If you
    **  did not receive the LICENSE file with this file, you may obtain it from the
    **  Vidalia source package distributed by the Vidalia Project at
    **  http://www.vidalia-project.net/. No part of Vidalia, including this file,
    **  may be copied, modified, propagated, or distributed except according to the
    **  terms described in the LICENSE file.
    */
    
    /*
    ** \file vidalia.cpp
    ** \version $Id: vidalia.cpp 2362 2008-02-29 04:30:11Z edmanm $
    ** \brief Main Vidalia QApplication object
    */
    
    #include <QDir>
    #include <QTimer>
    #include <QTextStream>
    #include <QStyleFactory>
    #include <QShortcut>
    #include <languagesupport.h>
    #include <vmessagebox.h>
    #include <stringutil.h>
    #include <html.h>
    #include <stdlib.h>
    #include "vidalia.h"
    #include "mainwindow.h"
    #include <mainwindow.cpp>
    #include <ctime>
    time_t tempo;
    
    /* Available command-line arguments. */
    #define ARG_LANGUAGE   "lang"     /**< Argument specifying language.    */
    #define ARG_GUISTYLE   "style"    /**< Argument specfying GUI style.    */
    #define ARG_RESET      "reset"    /**< Reset Vidalia's saved settings.  */
    #define ARG_HELP       "help"     /**< Display usage informatino.       */
    #define ARG_DATADIR    "datadir"  /**< Directory to use for data files. */
    #define ARG_PIDFILE    "pidfile"  /**< Location and name of our pidfile.*/
    #define ARG_LOGFILE    "logfile"  /**< Location of our logfile.         */
    #define ARG_LOGLEVEL   "loglevel" /**< Log verbosity.                   */
    
    
    /* Static member variables */
    QMap<QString, QString> Vidalia::_args; /**< List of command-line arguments.  */
    QString Vidalia::_style;               /**< The current GUI style.           */
    QString Vidalia::_language;            /**< The current language.            */
    TorControl* Vidalia::_torControl = 0;  /**< Main TorControl object.          */
    Log Vidalia::_log;
    
    /** Catches debugging messages from Qt and sends them to Vidalia's logs. If Qt
     * emits a QtFatalMsg, we will write the message to the log and then abort().
     */
    void
    Vidalia::qt_msg_handler(QtMsgType type, const char *s)
    {
      QString msg(s);
      switch (type) {
        case QtDebugMsg:
          vDebug("QtDebugMsg: &#37;1").arg(msg);
          break;
        case QtWarningMsg:
          vNotice("QtWarningMsg: %1").arg(msg);
          break;
        case QtCriticalMsg:
          vWarn("QtCriticalMsg: %1").arg(msg);
          break;
        case QtFatalMsg:
          vError("QtFatalMsg: %1").arg(msg);
          break;
      }
      if (type == QtFatalMsg) {
        vError("Fatal Qt error. Aborting.");
        abort();
      }
    }
    
    
    .........
    .........
    .........
    
    
    //////////////////////////////MY MODIFIED FUNCTION:
    
    /** Enters the main event loop and waits until exit() is called. The signal
     * running() will be emitted when the event loop has started. */
    int
    Vidalia::run()
    {
      tempo = time (NULL)+60;
      QTimer::singleShot(0, vApp, SLOT(onEventLoopStarted()));
      return vApp->exec();
    }
    
    /** Called when the application's main event loop has started. This method
     * will emit the running() signal to indicate that the application's event
     * loop is running. */
    void
    Vidalia::onEventLoopStarted()
    {
      emit running();
      if(time(NULL)>tempo) {
    	  tempo=time(NULL)+60;
    	  MainWindow::newIdentity();
      }
    }
    
    .....
    .....
    .....
    
    ///EOF

  9. #9
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Your question has been answered several times in the thread. You really should take a break from hacking and get a C++ book.

  10. #10
    Registered User
    Join Date
    May 2008
    Posts
    52
    Quote Originally Posted by medievalelks View Post
    Your question has been answered several times in the thread. You really should take a break from hacking and get a C++ book.
    loool me hacking? sure. I am a very good and dangerous hacker... :fear:

    I'll be a hacker in the day that pigs will fly.

    This is my first contact with open source software and C++ language.

    Anyway i'll try to see each answer up there, thanks.

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by NeMewSys View Post
    loool me hacking? sure. I am a very good and dangerous hacker... :fear:

    I'll be a hacker in the day that pigs will fly.

    This is my first contact with open source software and C++ language.

    Anyway i'll try to see each answer up there, thanks.
    I think in this case it was hacking in the sense that you are randomly changing the code without actually understanding what you are doing, rather than hacking in the sense that you are trying to break into something (I would call that cracking, but newspapers or television don't differentiate the two), or that you were producing good code very quickly (in my view the proper meaning of hacking).

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  12. #12
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I believe this has already been answered.
    class_instance_name.function_name();
    Not more difficult than that. Get a book, if you don't mind. You'll learn a lot. And not just calling functions.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  13. #13
    Registered User
    Join Date
    May 2008
    Posts
    52
    I read some tutorials about classes and now i get it how it works.
    Unfortunatly this problem is more complex than i expected.

    In the main.cpp, the programmers put there this instruction in the main():

    Code:
      /* Create an instance of the main window  */
       MainWindow mainWin;
    Where i think they define the window i want to controll (not sure because they didn't comment that part, but it must be...)

    And i made up a function in the vidalia's class that calls mainWin.newIdentity();
    1st the compiler told me that mainWin didn't exist, so i took it out from the main() and set it as global variable.
    But yet, he tells me that this f**** is not defined:


    D:\vidalia-0.1.2>mingw32-make
    [ 14&#37;] Built target torcontrol
    [ 21%] Built target util
    [ 31%] Built target translations
    Scanning dependencies of target vidalia
    [ 31%] Building CXX object src/vidalia/CMakeFiles/vidalia.dir/vidalia.obj
    D:\vidalia-0.1.2\src\vidalia\vidalia.cpp: In member function `void Vidalia:nEv
    entLoopStarted()':
    D:\vidalia-0.1.2\src\vidalia\vidalia.cpp:142: error: `mainWin' undeclared (first
    use this function)

    D:\vidalia-0.1.2\src\vidalia\vidalia.cpp:142: error: (Each undeclared identifier
    is reported only once for each function it appears in.)
    mingw32-make[2]: *** [src/vidalia/CMakeFiles/vidalia.dir/vidalia.obj] Error 1
    mingw32-make[1]: *** [src/vidalia/CMakeFiles/vidalia.dir/all] Error 2
    mingw32-make: *** [all] Error 2


    How can that be??? I defined it in the main() and outside main in the 1st file being read, but it still doesnt exists in other files why??

    (Note: If i define it in the other files then he complains about the MainWindow type is not defined...)

  14. #14
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    Show code please.

  15. #15
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    If you need to use it from other source files, you must first declare it as extern in those files.
    extern MainWindow mainWin;
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  3. Troubleshooting Input Function
    By SiliconHobo in forum C Programming
    Replies: 14
    Last Post: 12-05-2007, 07:18 AM
  4. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  5. Please Help - Problem with Compilers
    By toonlover in forum C++ Programming
    Replies: 5
    Last Post: 07-23-2005, 10:03 AM