Return currentTime using class

This is a discussion on Return currentTime using class within the C++ Programming forums, part of the General Programming Boards category; I'm trying to return the current Time using this class function, but it's not working. Any suggestions? Code: #include <iostream> ...

  1. #1
    Registered User Kayoss's Avatar
    Join Date
    Sep 2005
    Location
    California
    Posts
    53

    Return currentTime using class

    I'm trying to return the current Time using this class function, but it's not working. Any suggestions?

    Code:
    #include <iostream>
    #include <ctime>
    
    using namespace std;
    
    class Time 
    {
       public: 
    
         time_t currentTime; 
         time( &currentTime ); 
    
       void printTime()
       {
    	 cout << asctime( localtime( &currentTime));
       }
    
    }; 
    
    int main()
    {
       Time t; 
       t.printTime(); 
    
    return 0;
    }
    THE redheaded stepchild.

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    you're making the call to time in the definition of the class, perhaps you should move it inside a method?
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >but it's not working. Any suggestions?
    What do you mean by not working? Does it print the wrong value?

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Of course, it might help if you put the code in a constructor:
    Code:
       Time::Time()
       {
          time( &currentTime ); 
       }
    But if you want the current time when printTime() is called, then this call needs to go in printTime():
    Code:
       void printTime()
       {
    	 time( &currentTime ); 
    	 cout << asctime( localtime( &currentTime));
       }

  5. #5
    Registered User Kayoss's Avatar
    Join Date
    Sep 2005
    Location
    California
    Posts
    53
    Thank you very much! Constructors are now clearer to me.
    THE redheaded stepchild.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  2. deriving classes
    By l2u in forum C++ Programming
    Replies: 12
    Last Post: 01-15-2007, 04:01 PM
  3. Certain functions
    By Lurker in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2003, 12:26 AM
  4. opengl program as win API menu item
    By SAMSAM in forum Game Programming
    Replies: 1
    Last Post: 03-03-2003, 06:48 PM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21